1 父元素相对定位布局,子元素绝对定位布局。
<style>
.box1{
border : green 2px solid;
width: 700px;
height: 300px;
position: relative;
}
.box2{
border : red 40px solid;
width: 100px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
/*margin: -90px 0 0 -90px;*/
/*这里一半应该是-50px 考虑到border的宽度应该设置90px*/
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
总结:不管是已知宽高还是未知宽高都用translate属性设置垂直水平居中。有些教程在已知子元素宽度时用margin指定子元素宽度的一半(上例代码中注释部分,但是这却没有考虑盒子边框(border)的宽度。
2 利用弹性盒子优雅高效
<style>
.fa{
display: flex;
border : 2px solid green;
height: 500px;
width: 500px;
}
.son{
border : 2px solid red;
height: 50px;
width: 50px;
margin: auto;
}
</style>
</head>
<body>
<div class="fa">
<div class="son">我是子元素</div>
</div>
</body>
或者在父元素设置justify-content: center;和align-items: center;属性。
<!--弹性盒模型提供了比浮动布局更便利的布局方式-->
<style type="text/css">
#box{
background: deeppink;
height: 500px;
display: flex;
/*使用弹性盒子解决垂直水平居中问题*/
justify-content: center;
align-items: center;
/* 使用justify-content属性设置横轴排列方式
flex-start | flex-end | center | space-between | space-around;*/
/*align-items: flex-start | flex-end | center | baseline | stretch;*/
}
.box1{
height: 200px;
width: 200px;
background: black;
}.box2{
height: 200px;
width: 200px;
background: blue;
}.box3{
height: 200px;
width: 200px;
background: red;
}
</style>