结构:
1 <div class="parent"> 2 <div class="child">DEMO</div> 3 </div>
样式:
1.解决方案一:text-align + inline-block + table-cell + vertical-align(结合前面的水平居中+垂直居中)
1 .parent { 2 background-color: grey; 3 width: 300px; 4 height: 200px; 5 6 display: table-cell; 7 vertical-align: middle; 8 9 text-align: center; 10 } 11 .child { 12 display: inline-block; 13 background-color: skyblue; 14 }
2.解决方案二: absolute+transform
.parent { background-color: grey; width: 300px; height: 200px; position: relative; } .child { position: absolute; top: 50%;/*相对容器的百分比*/ left: 50%; transform: translate(-50%,-50%);/*相对自身的百分比*/ background-color: skyblue; }
3.解决方案三:flex + justify-content + align-items
.parent { background-color: grey; width: 300px; height: 200px; display: flex; justify-content: center; align-items: center; } .child { background-color: skyblue; }
时间: 2024-11-10 15:36:31