css中一个元素如何在其父元素居中显示
css中一个元素如何在其父元素居中显示
水平居中
水平垂直居中
水平居中
(1)在子元素上增加margin auto(被包裹的元素不能有浮动的属性。否则的话这个属性就会失效。)
<style>
body{margin: 0;}
.box{
width: 400px;
height: 400px;
border:1px solid red;
}
item{
margin:0 auto;
width: 100px;
height: 100x;
background: green;
}
</style>
<body>
<div class="box">
<div class="item"></div>
</div>
</body>
(2)这个属性在没有浮动的情况下,我们可以将其转换为inline/inline-block,然后其父元素加上text-align:center;属性就可以将其居中
<style>
body{margin: 0;}
.box{
width: 400px;
height: 400px;
border:1px solid red;
text-align:center;
}
item{
display:inline/inline-block;
width: 100px;
height: 100x;
background: green;
}
</style>
<body>
<div class="box">
<div class="item"></div>
</div>
</body>
水平垂直居中
子元素相对于父元素绝对定位,并且margin值减去自己宽高的一半(注释部分)
子元素相对于父元素绝对定位,并且margin值位auto,不受宽高限制(没注释部分)
div.son{
display: inline-block;
width: 50px;
height: 50px;
background-color: green;
opacity: 0.5;
position: absolute;
/*left: 50%;
top: 50%;
margin-top: -25px;
margin-left: -25px;*/
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
水平垂直居中
子元素相对于父元素绝对定位,并且transform: translate(-50%,-50%); 不受宽高限制(css3)
div.father{
width: 150px;
height: 150px;
background-color: red;
opacity: 0.5;
text-indent: center;
position: relative;
/*margin: 0 auto;*/
}
div.son{
/*display: inline-block;*/
width: 50px;
height: 50px;
background-color: green;
opacity: 0.5;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
结果如下:
水平垂直居中
在父元素上运用CSS3的flex属性:display: flex; justify-content: center; align-items: center;
div.father{
width: 150px;
height: 150px;
background-color: red;
opacity: 0.5;
text-indent: center;
position: relative;
/*margin: 0 auto;*/
display: flex; justify-content: center; align-items: center;
}
div.son{
/*display: inline-block;*/
width: 50px;
height: 50px;
background-color: green;
opacity: 0.5;
position: absolute;
}