首頁 > web前端 > css教學 > 主體

css如何實現水平垂直居中以及兩端對齊的程式碼分享

黄舟
發布: 2017-07-19 16:06:10
原創
1952 人瀏覽過

單行垂直居中

單行垂直居中可以直接用line-height=width來做

<p  style="width:100px;height:100px;line-height:100px;">
<span>hello world</span>
</p>
登入後複製

這樣文字hello world便實現了垂直居中,如果想讓整個p在父級元素中都居中,則在外面嵌套一層p,並且透過裡面p的margin來實現

<p style="position:relative;width:400px;height:200px;">
<p class="element" style="width:50%;height:50%;line-height:100px;">
<span>hello world</span>
</p>
</p>
.element {   position: absolute; left: 0; top: 0; right: 0; bottom: 0;   margin: auto 0;}
登入後複製

多行垂直居中

多行垂直居中的話用line-height就不行了。需要將p的display:table-cell,然後vertical-align:middle;

<p class="twoClass" >你好时间你好时间你好时间你好时间</p>
.twoClass{display:table-cell; width:200px; height:200px; vertical-align:middle;}
登入後複製

其實這種方法對於單行的垂直居中也是可行的。

水平居中

對於文本的水平居中,只要text-align:center;就可以了,如果將正個p居中,則需要將p的margin-left  margin-right設為auto

<p style="position:relative;width:200px;height:200px;">
<p class="element" style="width:50%;height:50%;text-align:center;line-height:100px;">你好时间</p></p>
.element {   position: absolute; left: 0; top: 0; right: 0; bottom: 0;   margin: auto auto;}
登入後複製

這個demo實作了p和文字的水平垂直居中。

兩端對齊

對於多行文字的兩端對齊,只需要text-align:justify就可以了

<p style="position:relative;width:100px;height:400px;text-align:justify;">
hello world he hello world你好世界你好世界你好世界, he hello world he hello你好世界你好世界你好世界, world he hello world he hello world he 
</p>
登入後複製

值得注意的是這個多行文字的最後一行並沒有兩端對齊。

如果想要對最後一行做操作,可以使用text-align-last: justify; 但是有相容性問題。

單行的兩端對齊

<p style="width:400px;text-align-last:justify;">
我好帅
</p>
登入後複製

沒想到一個text-align-last: justify;就實現了(chrome),但是在IE瀏覽器下並沒有效果。 。 。

下面這個是從網路上找的幾個a標籤兩端對齊

.demo{
     text-align-last:justify;
     line-height:0;
     height:44px;


}
.demo a{
     width:20%;
     display:inline-block;
     height:44px;
     line-height:44px;
     text-align:center;


}

<p>模块内的元素之间为换行符</p>
<br />
<p class="demo">
   <a class="link" href="#none">10元</a>
   <a class="link" href="#none">20元</a>
   <a class="link" href="#none">30元</a>
   <a class="link" href="#none">50元</a>
</p>
<br />
<p>模块内的元素之间为空格符</p>
<br />
<p class="demo">
<a class="link" href="#none">10元</a> <a class="link" href="#none">20元</a> <a class="link" href="#none">30元</a> <a class="link" href="#none">50元</a>
</p>
<br />
<p>模块内的元素之间为无分隔符,justify不起作用</p>
<br />
<p class="demo"><a class="link" href="#none">选项1</a><a class="link" href="#none">选项2</a><a class="link" href="#none">选项3</a><a class="link" href="#none">选项4</a></p>
登入後複製

以上是css如何實現水平垂直居中以及兩端對齊的程式碼分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!