1. 水平居中
(1)行内元素居中
父元素设置 text-align:center
示例代码:
<body>
<div class="parent">
<span class="son">sss</span>
</div>
</body>
<style>
.parent{
width: 500px;
height: 300px;
background-color: blueviolet;
}
.son {
width: 100px;
height: 100px;
background-color: yellow;
}
</style>
<style>
.parent{
text-align: center;
}
/* .son{
display: inline-block;
} */
</style>
效果图:
(2)块级元素居中
子元素: margin: 0 auto
;
代码:
<body>
<div class="parent">
<div class="son">sss</div>
</div>
</body>
<style>
.parent{
width: 500px;
height: 300px;
background-color: blueviolet;
}
.son {
width: 100px;
height: 100px;
background-color: yellow;
}
</style>
<style>
.parent{
text-align: center;
}
.son{
margin: 0 auto;
}
</style>
效果图:
请问:为什么 margin:auto 0;不能实现水平居中。
答:子元素宽度会默认占满父元素一行,而高度不会。
如下;
子元素宽度没有值时,默认占满一行;
<body>
<div class="parent">
<div class="son">sss</div>
</div>
</body>
<style>
.parent{
width: 500px;
height: 300px;
background-color: blueviolet;
}
.son {
/* width: 100px; */
height: 100px;
background-color: yellow;
}
</style>
<style>
.parent{
text-align: center;
}
/* .son{
margin: 0 auto;
} */
</style>
效果图:
子元素高度不设置值时,高度为自身内容高度。
<body>
<div class="parent">
<div class="son">sss</div>
</div>
</body>
<style>
.parent{
width: 500px;
height: 300px;
background-color: blueviolet;
}
.son {
width: 100px;
/* height: 100px; */
background-color: yellow;
}
</style>
<style>
.parent{
text-align: center;
}
/* .son{
margin: 0 auto;
} */
</style>
效果图: