块级元素使用margin:auto水平居中:
div {
width: 200px;
height: 200px;
margin: 0 auto;
}
块级元素margin:auto不能垂直居中的原因:
-
在 display: block 中,如果 margin-left 和 margin-right 都是 auto,则它们的计算值相等,从而导致元素的水平居中。( 这里的计算值为元素剩余可用剩余空间的一半)
-
而如果 margin-top 和 margin-bottom 都是 auto,则他们的值都为 0,当然也就无法造成垂直方向上的居中。
FFC(flex formatting context)/GFC(grid formatting context)中使 margin: auto 在垂直水平方向上居中元素
FFC|GFC指:
{
display: flex;
display: inline-flex;
display: grid;
display: inline-grid;
}
- 在flex格式化上下文中,设置了 margin: auto 的元素,在通过 justify-content 和 align-self 进行对齐之前,四个方向处于空闲的空间都会自动计算,并平均分配到该方向的自动 margin 中去
- 如果任意方向上的可用空间分配给了该方向的自动 margin ,则对齐属性(justify-content/align-self)在该维度中不起作用,因为 margin 将在排布后窃取该纬度方向剩余的所有可用空间。
- 即使用了 margin:auto 的 flex 子项目,它们父元素设置的 justify-content 以及它们本身的 align-self 将不再生效
在FFC/GFC自动计算分配剩余空间的基础上,利用margin实现justify-content和align-self的功能
<ul class="g-flex">
<li>liA</li>
<li>liB</li>
<li>liC</li>
<li>liD</li>
<li>liE</li>
</ul>
space-around
根据自动计算距离,则每个margin:auto看作1份,A左右各1份,B左右各1份,A和B直接的距离为2份,A左边为1份
.g-flex {
display: flex;
// justify-content: space-around;
}
li {
margin: auto;
}
效果图:
space-between
.g-flex {
display: flex;
// justify-content: space-between;
}
li {
...
margin: auto;
}
li:first-child {
margin-left: 0;
}
li:last-child {
margin-right: 0;
}
效果图:
space-evenly
子元素为奇数情况:首尾元素margin:autp左右各占1份,相邻元素一个margin:0,另一个margin:auto,达到份数相同,实现evenly效果
偶数情况需要一个一个单独计算份数,不作展示
.g-flex {
height: 200px;
box-sizing: border-box;
background: #037d65;
display: flex;
}
li {
width: 100px;
text-align: center;
font-size: 18px;
color: #fff;
margin: auto;
}
li:nth-child(1) {
height: 100px;
background: #336699;
}
li:nth-child(2) {
height: 120px;
background: #669933;
margin: 0;
}
li:nth-child(3) {
height: 140px;
background: #996633;
}
li:nth-child(4) {
height: 160px;
background: #229955;
margin: 0;
}
li:nth-child(5) {
height: 180px;
background: #199652;
}
效果图:
align-self: flex-start | flex-end | center
flex-center
.g-flex {
height: 200px;
box-sizing: border-box;
background: #037d65;
display: flex;
// justify-content: space-around;
}
li {
// align-self: center;
width: 100px;
text-align: center;
font-size: 18px;
color: #fff;
margin: auto;
}
flex-end
.g-flex {
height: 200px;
box-sizing: border-box;
background: #037d65;
display: flex;
// display: flex-inline;
// justify-content: space-around;
}
li {
// align-self: center;
width: 100px;
text-align: center;
font-size: 18px;
color: #fff;
margin: auto;
margin-bottom: 0;
margin-top: auto;
}
自定义两端布局
.g-nav {
display: flex;
}
.g-login {
margin-left: auto;
}
<ul class="g-nav">
<li>导航A</li>
<li>导航B</li>
<li>导航C</li>
<li>导航D</li>
<li class="g-login">登陆</li>
</ul>
局部根据剩余位置居中
.g-container {
display: flex;
flex-wrap: wrap;
flex-direction: column;
}
.s-thirf {
margin-top: auto;
}
.s-forth {
margin-bottom: auto;
}
<div class="g-container">
<p>这是第一行文案</p>
<p>这是第二行文案</p>
<p class="s-thirf">1、剩余多行文案需要垂直居中剩余空间</p>
<p class="s-forth">2、剩余多行文案需要垂直居中剩余空间</p>
<p>这是最后一行文案</p>
</div>