水平居中
- 行内元素
首先看父元素是不是块级元素,如果是
要实现水平居中,则直接给父元素设置 text-align:center;
<style>
.father{
text-align: center;
}
</style>
<body>
<div class="father">
<span class="son">行内元素</span>
</div>
</body>
效果:
附:此时我们发现父元素的大小完全由行内元素撑开。
父元素不是块级元素
将父元素设置为块级元素,再给父元素设置text-align:center;
- 块级元素
两种方案:
方案一、
分为宽度定不定两种情况
1.定宽度:需要谁居中,给其设置marigin:0 auto;
.sun{
width: 100px;
height: 100px;
background-color: red;
margin:0px auto;
}
</style>
<body>
<div class="sun"></div>
</body>
效果:
2.不定宽度:默认子元素的宽度和父元素一样,这时需要设置子元素为:display:inline-block或display:inline;即将其转换成行内块级/行内元素。给父元素设置text-align:center;
.father{
text-align: center;
width: 100px;
height: 100px;
background-color: red;
}
.sun{
background: green;
display: inline;
}
</style>
<body>
<div class="father">
<div class="sun">我是块级元素</div>
</div>
效果:
方案二、
使用定位属性
父元素为相对定位/绝对定位,在设置子元素为绝对定位。设置子元素的left:50%;
1.定宽度:设置绝对子元素的margin-left:-width/2;或者设置transforn:translateX(-50%);
<style>
.father{
position: relative;
width: 100px;
height: 100px;
background-color: aqua;
margin-left: 100px;
}
.son{
position: absolute;
width: 50px;
height: 50px;
background-color: red;
left: 50%;
margin-left: -25px;
}
</style>
<body>
<div class="father">
<div class="son">
</div>
</div>
</body>
效果:可以看出元素son是相对于father元素的水平居中。
2.不定宽
<style>
.father{
position: relative;
width: 300px;
height: 300px;
background-color: aqua;
margin-left: 100px;
}
.son{
position: absolute;
/* width: 50px; */
height: 50px;
background-color: red;
left:50%;
transform:translateX(-50%) ;
}
</style>
<body>
<div class="father">
<div class="son">
我是块级元素
</div>
</div>
效果:
子元素是相对定位的情况下
可以使用margin:0px auto;实现水平居中。
.father{
position: relative;
width: 300px;
height: 300px;
background-color: aqua;
margin-left: 100px;
}
.son{
position: relative;
width: 50px;
height: 50px;
background-color: red;
margin: 0px auto;
}
</style>
<body>
<div class="father">
<div class="son">
我是块级元素
</div>
</div>
</body>
效果
方案三、使用flex布局实现(宽度定不定都可以)
使用flexbox布局,只需要给待处理的块状元素的父元素添加属性display:flex;
justify-content:center;
<style>
.father{
width: 300px;
height: 300px;
background-color: aqua;
display: flex;
justify-content: center;
}
.son{
width: 50px;
height: 50px;
background-color: red;
}
</style>
<body>
<div class="father">
<div class="son">
我是块级元素
</div>
</div>
</body>
效果