当前位置: 代码迷 >> 综合 >> CSS盒模型垂直居中的方式(前提已知宽高情况下)
  详细解决方案

CSS盒模型垂直居中的方式(前提已知宽高情况下)

热度:111   发布时间:2023-10-27 11:28:12.0

1.flex布局

.box{height: 300px;width: 300px;border: 1px solid #000;margin: 50px auto;/* flex布局实现 */display: flex;align-items: center;justify-content: space-around; }.box1{width: 100px;height: 100px;background: #ccc;}

2.定位

.box{height: 300px;width: 300px;border: 1px solid #000;margin: 50px auto;/* 定位实现 父级开启相对定位,子级开启绝对定位,子级设置top,left值为(父级宽高-子级宽高)/2*/position: relative;}
.box1{width: 100px;height: 100px;background: #ccc;position: absolute;left: 100px;top: 100px;}

3.margin值

.box{height: 300px;width: 300px;border: 1px solid #000;margin: 50px auto;}.box1{width: 100px;height: 100px;background: #ccc;/* margin实现 */margin: 100px;}

4.设置transform属性配合margin值

.box{height: 300px;width: 300px;border: 1px solid #000;margin: 50px auto;}.box1{width: 100px;height: 100px;background: #ccc;/* transform属性 + margin实现 */transform: translateY(100px);margin-top: 100px;}

 

  相关解决方案