learning-note
learning-note copied to clipboard
margin-right: auto
今天我才知道原来 margin-right 和 margin-left 还有 auto 这个值,可能之前没怎么仔细看文档
文档的解释为 auto:水平(默认)书写模式下,其计算值取决于可用空间
也就是说它能取多少就取多少
在一个flex 布局中, 会出现这样一种情况,如下图

每次这种布局, 我一般是把左右看成两部分,左边包含两个div 右边包含一个div
然后父元素display:flex; justify-content: space-between; 或者中间再加一个div元素设置flex-grow:1来占据空白,这样就达到了效果,但是总感觉有些美中不足。
下面介绍一种新的方法:
html 代码:
<div class="box">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
css 代码:
.box {
display: flex;
margin: auto;
width: 600px;
height: 100px;
border: 1px solid teal;
justify-content: space-between;
}
.item {
height: 100%;
width: 100px;
background-color: red;
}
.item:nth-child(2) {
background-color: blue;
margin-right: auto;
}
利用margin-right: auto,来让中间的那个子元素的margin占据剩下的空间。