<!--html-->
<body>
<div class="box">
<img src="" alt="">
</div>
</body>
1.水平居中的 margin:0 auto;
用于子元素上的,前提是不受float影响
<style>
*{
padding: 0;
margin: 0;
}
.box{
width: 300px;
height: 300px;
border: 3px solid red;
/*text-align: center;*/
}
.box img{
display: block;
width: 100px;
height: 100px;
margin: 0 auto;
}
</style>
2.水平居中 text-align:center;
img的display:block;类似一样在不受float影响下进行
在父元素上添加效果让它进行水平居中
<style>
*{
padding: 0;
margin: 0;
}
.box{
width: 300px;
height: 300px;
border: 3px solid red;
/*text-align: center;*/
}
.box img{
display: block;
width: 100px;
height: 100px;
margin: 0 auto;
}
</style>
3.水平垂直居中(一)定位和需要定位的元素的margin减去宽高的一半
需要知道需要垂直居中的宽高才能实现,经常使用这种方法
<style>
*{
padding: 0;
margin: 0;
}
.box{
width: 300px;
height: 300px;
background:#e9dfc7;
border:1px solid red;
position: relative;
}
.box img{
width: 100px;
height: 150px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -75px;
margin-left: -50px;
}
</style>
4.水平垂直居中(二)定位和margin:auto;
<style>
*{
padding: 0;
margin: 0;
}
.box{
width: 300px;
height: 300px;
background:#e9dfc7;
border:1px solid red;
position: relative;
}
.box img{
width: 100px;
height: 100px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
5.水平垂直居中(三)绝对定位和transfrom
元素宽高未知时常用,已知也可用,因逼格很高 ~~
<style>
*{
padding: 0;
margin: 0;
}
.box{
width: 300px;
height: 300px;
background:#e9dfc7;
border:1px solid red;
position: relative;
}
.box img{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
6.水平垂直居中(四)diplay:table-cell
利用表格的样式来进行居中,很方便
<style>
.box{
width: 300px;
height: 300px;
background:#e9dfc7;
border:1px solid red;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.box img{
width: 100px;
height: 150px;
/*margin: 0 auto;*/ 这个也行
}
</style>
7.水平垂直居中(五)flexBox居中
利用CSS3属性flex布局,非常方便快捷,在移动端使用完美,pc端有兼容性问题,以后会成为主流
<style>
.box{
width: 300px;
height: 300px;
background:#e9dfc7;
border:1px solid red;
display: flex;
justify-content: center;
align-items:center;
}
.box img{
width: 150px;
height: 100px;
}
</style>