htmlcss
<html> <head> <title>水平垂直居中的全部方法</title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="./style/index.css"> </head> <body> <fieldset> <legend>flex佈局</legend> <div class="flex-box"> <img src="./imgs/timg.jpg" alt="卡通圖案"> </div> </fieldset> <fieldset> <legend>應用translate</legend> <div class="translate-box"> <img src="./imgs/timg.jpg" alt="卡通圖案"> </div> </fieldset> <fieldset> <legend>純absolute佈局</legend> <div class="absolute-box"> <img src="./imgs/timg.jpg" alt="卡通圖案"> </div> </fieldset> <fieldset> <legend>table-cell</legend> <div class="table-box"> <div class="inner-table-box"> <img src="./imgs/timg.jpg" alt="卡通圖案"> </div> </div> </fieldset> <fieldset> <legend>calc</legend> <div class="calc-box"> <img src="./imgs/timg.jpg" alt="卡通圖案"> </div> </fieldset> </body> </html>
csshtml
fieldset{
float: left;
}
div{
border: 1px solid #ccc;
height: 300px;
width: 300px;
}
img{
width: 100px;
}
.flex-box{
display: flex;
}
.flex-box img{
margin: auto;
}
.translate-box{
position: relative
}
.translate-box img{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
.absolute-box{
position: relative;
}
.absolute-box img{
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.table-box{
display: table;
}
.inner-table-box{
display: table-cell;
text-align: center;
vertical-align: middle;
}
.calc-box{
position: relative;
}
.calc-box img{
position: absolute;
top:calc(50% - 50px);
left:calc(50% - 50px);
}
github 地址:https://caraxiong.github.io/css-center/src/index.htmlgit