css实现水平居中的不同类型的方式总结
1.普通文本
text-align: center;
2.行内元素
text-align: center;
3.图片:行内替换元素
text-align: center;
4.行内块级元素:inline-block
text-align: center;
5.块级元素(在自身元素中添加该属性值)
margin: 0 auto;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
height: 200px;
background-color: #f00;
/* 1.普通文本 */
/* text-align: center; */
/* 2.行内元素 */
/* text-align: center; */
/* 3.图片:行内替换元素 */
/* text-align: center; */
/* 4.行内块级元素:inline-block */
/* text-align: center; */
text-align: center;/* 会让‘box’div的块级元素继承该属性导致文字居中 */
}
strong {
background-color: purple;
}
.ib {
display: inline-block;
width: 100px;
height: 100px;
background-color: orange;
}
.block {
background-color: yellowgreen;
width: 100px;
height: 100px;
/* 5.块级元素(在自身元素中添加该属性值) */
/* margin俩个值含义:(上下边距),(左右边距) */
margin: 0 auto;
}
</style>
</head>
<body>
<div class="box">
<!-- 1.普通文本 -->
<!-- div元素 -->
<!-- 2.行内元素 -->
<!-- <strong>strong元素<strong> -->
<!-- 3.图片:行内替换元素 -->
<!-- <img src="" alt=""> -->
<!-- 4.行内块级元素:inline-block -->
<!-- <span class="ib">哈哈哈</span> -->
<!-- 5.块级元素 -->
<div class="block">哈哈哈</div>
<span>呵呵呵</span>
</div>
</body>
</html>
margin:0 auto实现居中的原理:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
height: 200px;
width: 800px;
background-color: #f00;
}
.inner {
width: 150px;
height: 100px;
background-color: #ff0;
/*margin-left/right的初始值是0
margin-left/right: auto;剩余空间都自动分配 */
/* 可以实现水平居中*/
margin-left: auto;
margin-right: auto;
/* 注意:实现不了垂直居中 */
margin-top: auto;
margin-bottom: auto;
}
</style>
</head>
<body>
<div class="box">
<div class="inner"></div>
</div>
</body>
</html>