Fork me on GitHub

CSS居中的几种方式

水平居中 margin:0 auto

<style>
*{
padding: 0;
margin: 0;
}
.box{
width: 300px;
height: 300px;
border: 3px solid red;
/*text-align: center;*/
}
img{
display: block;
width: 100px;
height: 100px;
margin: 0 auto;
}
</style>

<!--html-->
<body>
<div class="box">
<img src="1.jpg">
</div>
</body>

水平居中 text-align:center

<style>
*{
padding: 0;
margin: 0;
}
.box{
width: 300px;
height: 300px;
border: 3px solid red;
text-align: center;
}
img{
display: inline-block;
width: 100px;
height: 100px;
/*margin: 0 auto;*/
}
</style>

<!--html-->
<body>
<div class="box">
<img src="1.jpg">
</div>
</body>

水平垂直居中 定位和需要定位的元素的margin减去宽高的一半(需要知道宽高)

<style>
*{
padding: 0;
margin: 0;
}
.box{
width: 300px;
height: 300px;
background:#e9dfc7;
border:1px solid red;
position: relative;

}
img{
width: 100px;
height: 100px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>

<!--html -->
<body>
<div class="box" >
<img src="1.jpg">
</div>
</body>

水平垂直居中 绝对定位和transform(不需要知道宽高)

<style>
*{
padding: 0;
margin: 0;
}
.box{
width: 300px;
height: 300px;
background:#e9dfc7;
border:1px solid red;
position: relative;
}
img{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>

<!--html -->
<body>
<div class="box" >
<img src="1.jpg">
</div>
</body>