我有两个可变宽度的元素,我试图按以下方式定位:
简单的事情:
<div class="container">
<div style="display: inline-block;">
I'm a variable width left element
</div>
<div style="display: inline-block; float:right;">
I'm right-floating if there's space
</div>
</div>
处理第一种情况,但显然当容器足够小以使第二个div在第一个div下面呈现时,它仍然是正确浮动的,这不是我想要的。
纯CSS还能实现这一点吗?由于未知/可变宽度,我无法使用媒体查询。
答案 0 :(得分:3)
这种布局和行为可以使用flexbox进行无媒体查询和纯CSS 。
<强> HTML 强>
<!-- horizontal alignment when two boxes fit -->
<div class="container">
<div class="box box1"><span>1</span></div>
<div class="box box2"><span>2</span></div>
</div>
<!-- vertical alignment when two boxes don't fit -->
<div class="container">
<div class="box box3"><span>1</span></div>
<div class="box box4"><span>2</span></div>
</div>
<强> CSS 强>
.container {
display: flex;
justify-content: space-between;
flex-wrap: wrap;
width: 700px; /* for demo only; can be relative length, as well */
}
.box1 { width: 100px; }
.box2 { width: 150px; }
.box3 { width: 400px; }
.box4 { width: 500px; }
注意:
如果有足够的空间来容纳同一行上的两个可变宽度元素,则它们会在容器的两端与justify-content: space-between
对齐。
当没有足够的空间来容纳这两个元素时,它们会以flex-wrap: wrap
和align-left包裹,因为justify-content: space-between
规则会左对齐一个元素当它独自在行上时。
请注意,所有主流浏览器except IE 8 & 9都支持flexbox。最近的一些浏览器版本,例如Safari 8和IE10,需要vendor prefixes。要快速添加所需的所有前缀,请在左侧面板中发布CSS:Autoprefixer。