一、垂直居中和水平居中
1.垂直居中
(1)纯文字可以利用line-height=height;来实现垂直居中
(2)父盒子相对定位,子盒子绝对定位。margin: auto法
.Center-Container {
width: 1000px;
height: 500px;
background-color: pink;
position: relative;
margin: 0 auto;
}
.Absolute-Center {
width: 60%;
height: 60%;
background-color: blue;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
(3)父盒子相对定位,子盒子绝对定位。负外边距法。适合图片
.Center-Container {
width: 1000px;
height: 500px;
background-color: pink;
position: relative;
margin: 0 auto;
}
.Absolute-Center {
width: 300px;
height: 200px;
background-color: blue;
position: absolute;
top: 50%;
left: 50%;
margin-left: -150px;
margin-top: -100px;
}
(4)父盒子相对定位,子盒子绝对定位。负外边距之transform法。适合图片
.Center-Container {
width: 1000px;
height: 500px;
background-color: pink;
position: relative;
margin: 0 auto;
}
.Absolute-Center {
width: 50%;
height: 50%;
background-color: blue;
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
(5)弹性布局法。父盒子设置display: flex; 子级设置margin:auto实现自适应居中;适合图片
.Center-Container {
width: 1000px;
height: 500px;
background-color: pink;
margin: 0 auto;
display: flex;
}
.is-Center {
width: 200px;
height: 50%;
background-color: blue;
margin: auto;
}
(6)表格单元格table法。需要将居中的内容/图片放在第三层里面
<style>
.Center-Container {
width: 1000px;
height: 500px;
display: table;
background-color: pink;
}
.is-Center {
display: table-cell;
/* 垂直对齐表格单元内容: */
vertical-align: middle;
text-align: center;
}
</style>
</head>
<div class="Center-Container">
<div class="is-Center ">
<!-- <p>我爱你</p>
<p>亲爱的中国</p> -->
<img src="images/img.jpg" alt="">
</div>
</div>