CSS将div内容垂直居中案例总结(css使div垂直居中)居然可以这样

随心笔谈12个月前发布 admin
85 0



如果要垂直居中的只有一行或几个文字,那它的制作最为简单,只要让文字的行高和容器的高度相同即可,比如:

p { height:30px; line-height:30px; width:100px; overflow:hidden; }

这段代码可以达到让文字在段落中垂直居中的效果。

另一种方法和行高法很相似,它同样适合一行或几行文字垂直居中,原理就是利用padding将内容垂直居中,比如:

p { padding:20px 0; }

这段代码的效果和line-height法差不多。

将容器设置为display:table,然后将子元素也就是要垂直居中显示的元素设置为display:table-cell,然后加上vertical-align:middle来实现。

html结构如下:

<div id=”wrapper”>
<div id=”cell”>
<p>测试垂直居中效果测试垂直居中效果</p>
<p>测试垂直居中效果测试垂直居中效果</p>
</div>
</div>

css代码:

#wrapper {display:table;width:300px;height:300px;background:#000;margin:0 auto;color:red;}
#cell{display:table-cell; vertical-align:middle;}

实现如图所示:

CSS将div内容垂直居中案例总结(css使div垂直居中)居然可以这样

遗憾的是IE7及以下不支持。

css代码如下:

.center-vertical{
position: relative;
top:50%;
transform:translateY(-50%);
}.center-horizontal{
position: relative;
left:50%;
transform:translateX(-50%);
}

html代码:

<div class=”center”>
<div class=”text”>
<p>我是多行文字</p>
<p>我是多行文字</p>
<p>我是多行文字</p>
</div>
</div>

css代码:

.center {
width: 300px;
height: 200px;
padding: 10px;
border: 1px solid #ccc;
background:#000;
color:#fff;
margin: 20px auto;

display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-pack: center;
-webkit-box-align: center;

display: -moz-box;
-moz-box-orient: horizontal;
-moz-box-pack: center;
-moz-box-align: center;

display: -o-box;
-o-box-orient: horizontal;
-o-box-pack: center;
-o-box-align: center;

display: -ms-box;
-ms-box-orient: horizontal;
-ms-box-pack: center;
-ms-box-align: center;

display: box;
box-orient: horizontal;
box-pack: center;
box-align: center;
}

 结果如图:

CSS将div内容垂直居中案例总结(css使div垂直居中)居然可以这样

html代码:

<div class=”flex”>
<div>
<p>我是多行文字我是多行文字我是多行文字我是多行文字</p>
<p>我是多行文字我是多行文字我是多行文字我是多行文字</p>
</div>
</div>

CSS代码:

.flex{

display: flex;

align-items: center;

justify-content: center;

text-align: justify;
width:200px;
height:200px;
background: #000;
margin:0 auto;
color:#fff;
}

实现效果:

CSS将div内容垂直居中案例总结(css使div垂直居中)居然可以这样

到此这篇关于CSS将div内容垂直居中案例总结的文章就介绍到这了,更多相关CSS将div内容垂直居中内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:C语言中lseek()函数和fseek()函数的使用详解JavaScript navigator.userAgent获取浏览器信息案例讲解一篇文章告诉你如何用python进行自动化测试,调用c程序Android startActivityForResult的基本用法详解CPU,GPU,DPU,TPU,NPU,BPU等处理器的性能及概念一篇文章告诉你如何用Python控制Excel实现自动化办公docker实现redis集群搭建的方法步骤C语言lseek()函数详解

© 版权声明

相关文章