1. 程式人生 > >css 水平垂直居中 兩端對齊

css 水平垂直居中 兩端對齊

單行垂直居中

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

<div  style="width:100px;height:100px;line-height:100px;">
<span>hello world</span>
</div>

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

<div style="position:relative;width:400px;height:200px;">
<div class="element" style="width:50%;height:50%;line-height:100px;">
<span>hello world</span>
</div>
</div>

.element {
   position: absolute; left: 0; top: 0; right: 0; bottom: 0;
   margin: auto 0;
}

多行垂直居中

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

<div class="twoClass" >
你好時間你好時間你好時間你好時間
</div>

.twoClass{display:table-cell; width:200px; height:200px; vertical-align:middle;}

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

水平居中

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

<div style="position:relative;width:200px;height:200px;">
<div class="element" style="width:50%;height:50%;text-align:center;line-height:100px;">
你好時間
</div>
</div>

.element {
   position: absolute; left: 0; top: 0; right: 0; bottom: 0;
   margin: auto auto;
}

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

兩端對齊

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

<div 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 
</div>

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

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

單行的兩端對齊

<div style="width:400px;text-align-last:justify;">
我好帥
</div>

沒想到一個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 />
<div 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>
</div>
<br />
<p>模組內的元素之間為空格符</p>
<br />
<div 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>
</div>
<br />
<p>模組內的元素之間為無分隔符,justify不起作用</p>
<br />
<div 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></div>