如何让盒子居中?
1、block元素,使用margin属性
.center {
margin: auto;
width: 90%;
border: 3px solid #73AD21;
padding: 10px;
}
<div class="center">
<p>我是居中盒子,当width为100%时,margin属性失效。但是盒子还是处于居中状态</p>
</div>
</body>
</html>
2、block元素,在flex容器上使用justify-content:center
注意,不要再元素加fle:1,否则会无法调节div块儿的宽度。以下代码同时可以让div盒子垂直居中
<div class="first">
<div class="second">
ddd
</div>
</div>
<style type="text/css">
.first {
width: 200px;
height: 200px;
background: rgba(255, 255, 0, 0.5);
display: flex;
justify-content: center;
align-items: center; //配合下方的指定高度样式,可以让div同时垂直居中
}
.second {
/*flex: 1;*/
background: pink;
height: 50%;
}
</style>
3、block 元素,绝对定位、margin-left:-(width/2)和left:50%实现水平居中:
<div class="first">
</div>
<style type="text/css">
.first {
width: 200px;
height: 50px;
position: absolute;
left: 50%;
margin-left: -100px;
background: pink;
}
</style>
4、inline-block元素,在父级块级元素上使用text-align:center
div{
text-align:center;
}
<div><span>ddd</span></div>
5、inline-block元素,两个元素都设置为inline-block,并且设置vertical-align: center。如此,这两个元素的中线就在同一水平线上,其中一个的高度和父容器同高,则另一个就是相对父容器垂直居中。
6、任意类型元素。left:50%+tranfrom:translateX(-50%)
<template>
<div class="box">
<div class="center">
</div>
</div>
</template>
<script>
</script>
<style lang="scss" scoped="scoped">
.box{
width: 90%;
height: 20%;
background: red;
position: relative;
.center{
width: 10%;
height: 100%;
background: green;
position: absolute;
left: 50%;
transform: translateX(-50%);
}
}
</style>
网友评论