1. 定位 + 负外边距
原理:元素设置定位并给定 50% 的top值和left值,再通过 负margin 将元素向左上移动自身宽高的一半,要知道子元素的宽度和高度 。
<style>
.father{
+ position:relative; // 绝对定位
width: 200px;
height: 200px;
background-color: pink;
}
.son{
+ position: absolute; // 相对定位
+ top: 50%;
+ left: 50%;
width: 60px;
height: 60px;
+ margin-left: -30px;
+ margin-top: -30px;
background-color: skyblue;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
2. 定位 + 平移
原理:使用CSS3新增属性 transform 中的 translate 平移属性,根据自身尺寸进行移动,缺点是由于为新增属性,兼容性自然就不是很好,远古IE不支持。
<style>
.father{
position:relative; // 绝对定位
width: 200px;
height: 200px;
background-color: pink;
}
.son{
position: absolute; // 相对定位
top: 50%;
left: 50%;
+ transform: translate(-50%,-50%); // 2D转换,平移
width: 60px;
height: 60px;
background-color: skyblue;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
3. margin:auto
原理:该方法的关键点是:1.绝对定位的(top、right、bottom、left)四个属性均要设置值为0;2.margin:auto,能够适用单个元素或者父子级元素,设置绝对定位并添加 margin:auto 属性就能够实现水平垂直居中,元素可自定义宽高,也可不设置(需要是自身存在尺寸的元素:img等)
<style>
.father{
position:relative; // 绝对定位
width: 200px;
height: 200px;
background-color: pink;
}
.son{
position: absolute; // 相对定位
+ top: 0;
+ bottom:0;
+ left: 0;
+ right: 0;
+ margin: auto;
width: 60px;
height: 60px;
background-color: skyblue;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
4. flex布局
原理:通过给父元素设置display为flex,再设置 item 的主轴和辅轴的对齐方式,兼容性也不是很好(IE8+ 及大众浏览器),大多数用于移动端布局
<style>
.father{
+ display: flex; // flex布局
+ justify-content: center; // 定义了项目在主轴上的对齐方式。
+ align-items: center; // 定义了项目在侧轴上的对齐方式。
width: 200px;
height: 200px;
background-color: pink;
}
.son{
width: 60px;
height: 60px;
background-color: skyblue;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
或
<style>
.father{
+ display: flex; // flex布局
width: 200px;
height: 200px;
background-color: pink;
}
.son{
+ margin: auto;
width: 60px;
height: 60px;
background-color: skyblue;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>