居中并右对齐Flexbox元素
我想让A
B
和C
在中间对齐。
我怎样才能让D
完全向右走?
之前:
后:
这样做的最佳做法是什么?
ul {
padding: 0;
margin: 0;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
li {
display: flex;
margin: 1px;
padding: 5px;
background: #aaa;
}
li:last-child {
background: #ddd;
/* magic to throw to the right*/
}
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
</ul>
以下是实现此布局的五个选项:
flex: 1
Flexbox flex: 1
方法#1:CSS定位属性
应用position: relative
对于柔性容器。
申请position: absolute
项目D.
现在这个项目绝对位于flex容器内。
更具体地说,项目D从文档流中被移除,但是停留在最近的定位祖先的界限内。
使用top
和right
的CSS偏移属性将此元素移动到位。
li:last-child {
position: absolute;
top: 0;
right: 0;
background: #ddd;
}
ul {
position: relative;
padding: 0;
margin: 0;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
li {
display: flex;
margin: 1px;
padding: 5px;
background: #aaa;
}
p {
text-align: center;
margin-top: 0;
}
span {
background-color: aqua;
}
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
</ul>
<p><span>true center</span></p>
非常明确的问题。 挖了几个小时之后,我忍不住发布了答案。 我们可以通过表格,表格单元格,绝对位置,转换来解决这个问题,但我们只能用flexbox来完成它:)
.parent {
display: flex;
justify-content: flex-end;
}
.center {
margin: auto;
}
http://codepen.io/rgfx/pen/BLorgd
链接地址: http://www.djcxy.com/p/76043.html