不定寬高垂直水平居中的幾種方法
阿新 • • 發佈:2018-12-01
-
父子定位,子元素使用 transfrom:translate();屬性
.box { width: 700px; height: 700px; border: 1px solid red; margin: 50pxauto; position: relative; } .box1 { width: 100px; height: 100px; background-color: green; position: absolute; left: 50%; top:50%; transform: translate(-50%, -50%); }
父子定位,子元素使用 left right top bottom margin: auto;屬性
.box { width: 700px; height: 700px; border: 1px solid red; margin: 50pxauto; position: relative; } .box1 { width: 100px; height: 100px; background-color: green; position: absolute; top: 50%; left: 50%; margin-left: -50px; margin-top: -50px; }
- 使用 flex 佈局
.box {
width: 700px;
height: 700px;
border: 1px solid red;
margin: 50px auto;
display: flex;
justify-content: center;
align-items: center;
}
.box1 {
width: 100px;
height: 100px;
background-color: green;
}