我在父包装器中有 2 个div。我想提出以下几点:
-
这两个div共享100%的宽度空间,因此它们之间没有间隙,一切都是红色的。
-
当您缩小包装器时,div b 会落入div a 下方的新行(这表现得像它应该的那样),但在这种情况下,我希望两个div 都是 100% 宽度,所以它们会变成 2 行红色。
是否可以仅使用css(没有表格!)而没有其他元素来做到这一点?
使包装器背景颜色为红色以补偿这一点不是解决方案。
<div class="wrapper">
<div class="a">left</div>
<div class="b">right</div>
</div>
http://jsfiddle.net/EAkLb/75/
只需将 a
和 b
的 CSS 更改为 width:50%;
,添加一个媒体查询以在较小的视口将它们设置为 100%。
.wrapper{
position: relative;
max-width: 400px;
height:30px;
background-color: #fff;
}
.a{
float: left;
background-color: red;
text-align: left;
width:50%;
height:30px;
}
.b{
float: right;
background-color: red;
text-align: right;
width:50%;
height:30px;
}
@media screen and (max-width: 500px) {
.a, .b {
width: 100%;
}
}
<div class="wrapper">
<div class="a">left</div>
<div class="b">right</div>
</div>
Flexbox 可以做到这一点:
JsFiddle 演示
.wrapper {
position: relative;
max-width: 400px;
height: 30px;
background-color: #fff;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.a {
background-color: red;
text-align: left;
flex: 0 0 110px;
height: 30px;
}
.b {
background-color: red;
text-align: right;
flex: 0 0 120px;
height: 30px;
}
@media screen and (max-width: 400px) {
.a,
.b {
flex: 1 0 100%;
}
}
<div class="wrapper">
<div class="a">left</div>
<div class="b">right</div>
</div>
考虑到您正在使用 CSS 媒体查询,您可以简单地更改divs 的宽度和 css float 属性。这不是现代的方式,但这是工作。
.wrapper{
position: relative;
max-width: 400px;
height:30px;
background-color: #fff;
}
.a, .b {
float: left;
width: 50%;
}
.a{
background-color: red;
text-align: left;
height:30px;
}
.b{
background-color: red;
text-align: right;
height:30px;
}
@media screen and ( max-width: 400px ) {
.a, .b {
float: none;
width: 100%;
}
}
flex
的美妙之处在于通常可以避免媒体查询。
将flex
与min-width
和flex-wrap
结合使用,我们可以在没有媒体查询的情况下达到所需的效果。
.wrapper{
position: relative;
max-width: 400px;
height:30px;
background-color: #fff;
display: flex;
flex-wrap: wrap;
}
.child {
flex-grow: 1;
background-color: red;
height:30px;
}
.a{
min-width:110px;
text-align: left;
}
.b{
min-width:120px;
text-align: right;
}
<div class="wrapper">
<div class="child a">left</div>
<div class="child b">right</div>
</div>
这是一个JSFiddle。
我的解决方案也使用 Flex - 但我使用最小宽度属性来告诉 flex 容器何时切换到 2 行
.wrapper{
position: relative;
max-width: 100%;
height:30px;
background-color: #fff;
display: flex;
flex-wrap:wrap ;
}
.a,.b {
background-color: red;
width:50%;
min-width:130px;
height:30px;
flex-grow:1;
flex-shrink:0;
flex-basis:50%
}
.b {
background-color:green;
text-align:right;
}
小提琴
使用滑块缩小窗口我用绿色作为"b"元素的背面