2019-08-25--鄙人整理了各种情况下的box居中(包括水平和垂直)的代码,在这里和大家分享一下,希望能给各位带来帮助:
水平居中:
1)块级元素水平居中:
html代码:
<div class="parent">
<div class="child">中间是我的</div>
</div>
css代码:
.parent {
width: 200px;
height: 100px;
border: 1px solid;
}
.child {
border: 1px solid blue;
margin: 0 auto;
height: 50px;
width: 80px;
}
2)浮动元素水平居中:
html代码:
<div class="parent">
<div class="child">我是浮动的,并且不知道宽高的元素,来气不!</div>
</div>
css代码:
.parent {
float: left;
position: relative;
left: 50%;
}
.child {
float: left;
position: relative;
right: 50%;
}
3)绝对定位元素水平居中:
html代码:
<div class="parent">
<div class="child"></div>
</div>
css代码:
.parent {
/* 子级绝对定位,父级需相对定位 */
position: relative;
width: 600px;
height: 250px;
line-height: 250px;
display: inline-block;
background-color: yellow;
}
.child {
display: inline-block;
position: absolute;
width: 150px;
height: 120px;
background: blue;
margin: 0px auto;
left: 0;
right: 0;
}
4)行级元素水平居中:
html代码:
<div class="parent">
<div class="child">行级元素水平居中</div>
</div>
css代码:
.parent {
width: 200px;
height: 100px;
border: 1px solid;
text-align: center;
}
.child {
display: inline;
border: 1px solid;
}
垂直居中:
1)块级元素垂直居中:
html代码:
<div class="parent">
<div class="child"></div>
</div>
css代码:
.parent {
width: 500px;
height: 300px;
line-height: 300px;
border: 1px solid;
/* 加上以下样式可水平垂直都居中 */
/* text-align: center; */
}
.child {
background: blue;
width: 300px;
height: 100px;
display: inline-block;
vertical-align: middle;
}
1)行级元素内容垂直居中:
html代码:
<p class="demo">
我会垂直居中的哟
</p>
css代码:
.demo {
width: 200px;
height: 200px;
line-height: 200px;
background-color: aqua;
}
小结:这里只是总结了一些常见的居中样式,若大家还有可以给我留言或提问给我,我希望把各种情况都总结一下,做一个归纳,便于大家以后使用方便!谢谢大家了!!!