在制作网页的时候,我们会需要给div标签各种方式的居中布局,以下分享了几种常见的几种居中方式,以及居中的方法。
1、实现垂直居中
当标签元素为文本或图片时我们可以直接在父元素css中设置text-align:center实现水平居中,或者使用display:inline-block将div标签内的子标签元素设置指定为行内元素,但如果行内元素设置了指定宽度text-align:center就没有作用这时候可以通过设置css中的margin属性实现居中.
<style>
.jz-a{
text-align: center;
height: 50px;
line-height: 50px;
}
</style>
<div class="jz-a"> <span>这是一段文字</span> </div>
或者
<style type="text/css">
.jz-b {
margin-left: auto;
margin-right: auto;
width: 300px;
}
</style>
<div class="jz-b">这是一段文字</div>
2、标签垂直居中
与水平居中的方式差不多,首先子元素是一个行内元素,高度由内容自定义,可以使用line-height设置垂直居中。
<div class="cz-line"> <span class="cz-line2">111111111111111</span> </div>
<style type="text/css">
.cz-line {
width: 100px;
height: 200px;
line-height: 200px;
border: 1px solid #118330;
}
.cz-line2 {
background:#0548E3;
}
</style>
或者
子标签元素是块级元素,但没有设置指定的高度,可以通过给父元素css属性设定display来解决.
<div class="zz-a">
<div class="zz-b">2222222222</div>
</div>
<style type="text/css">
.zz-a {
width: 100px;
height: 200px;
border: 1px solid #304484;
display: table-cell;
vertical-align: middle;
}
.zz-b {
background:#27E4A1;
}
</style>
全屏垂直居中
<style>
#eee {
background:#0B858B;
border: 1px solid #118330;
width: 320px;
height: 320px;
position: absolute;
margin: -160px;
}
#ccc {
height: 0px;
width: 0px;
top: 50%;
left: 50%;
position: absolute;
}
</style>
<div id="ccc">
<div id="eee">www.qtool.net</div>
</div>
以上就是常见的几种在网页布局中常用的居中方式.