您好,欢迎来到欧得旅游网。
搜索
您的当前位置:首页css如何实现水平垂直居中以及两端对齐的代码分享

css如何实现水平垂直居中以及两端对齐的代码分享

来源:欧得旅游网

单行垂直居中

单行垂直居中可以直接用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>

Copyright © 2019- ovod.cn 版权所有 湘ICP备2023023988号-4

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务