水平居中沒有什麼好說的啦,對於行內元素使用text-align;對於塊級元素使用margin: auto(前提是已經爲元素設置了適當的 width 寬度);javascript
line-height == height
<div class="parent"> <span class="child">etttttttttttttttttttttttttttttttttttttttttttttgdfsffffffffffffffffffffffffffffffffffffffffffffffffff</span> </div> .parent { height: 250px; text-align: center; border: 1px solid; } .parent:before { content: " "; height: 100%; display: inline-block; vertical-align: middle; } .child { width: 200px; display: inline-block; word-wrap: break-word; border: 1px solid; vertical-align: middle; }
<div class="parent"> <img class="child" src="./images/7.png"/> </div> .parent { line-height: 200px; } .child { vertical-align: middle; }
<div class="parent"> <img class="child" src="./images/7.png"/> </div> .parent { height: 200px; border: 1px solid; } .parent:before { content: " "; height: 100%; display: inline-block; vertical-align: middle; } .child { vertical-align: middle; }
<div class="parent"> <img class="child" src="./images/7.png"/> </div> .parent { height: 200px; border: 1px solid; display: table-cell; vertical-align: middle; } .child { vertical-align: middle; }
.parent { position: relative; } .child { position: absolute; left: 0; top: 0; right: 0; bottom: 0; margin: auto; }
.parent { position: relative; } .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); }
.parent { display: flex; justify-content: center; align-items: center; }
.parent { display: grid; justify-content: center; align-items: center; }
要考慮兼容性java
.parent { position: relative; } .child { position: absolute; top: 50%; left: 50%; margin: -height/2 -width/2; }
.parent { padding: (parent.height-child.height)/2 (parent.width-child.width)/2; }
.parent { position: relative; } .child { position: absolute; top: calc(50% - height/2 ); left: calc(50% - height/2 ); }
#demo { width: 300px; height: 200px; background-color: grey; display: table-cell; vertical-align: middle; } .fl { float: left; width: 50px; height: 50px; background-color: black; } <div id="demo"> <div class="fl"></div> </div>