【问题标题】:Pure CSS solution to push the middle of 3 items down将 3 项中间下推的纯 CSS 解决方案
【发布时间】:2016-04-29 00:47:07
【问题描述】:

好的,我的情况如下:

我使用 flexbox 连续有 3 个 div: 1 | 2 | 3

div 1 的宽度是固定的。 Div 2 'flexes' 以占用13 之间的可用空间,但至少应为其内容的大小(变化)。 div 3 需要是它所包含的内容的宽度,因人而异。

所以我有:

1 (fixed with) | 2 (flexes, but minimal width should be the width of the content) | 3 (width of content)

我想要实现的是,如果所有三个 div 所在的容器变得太小而无法满足每个 div 的最小宽度要求,则将中间部分(div 2)向下推。所以我得到:

1 | 3
-----
  2

我知道如何使用 javascript 来实现这一点,但是如果知道我事先不知道 23 内容的宽度,这是否可能使用纯 CSS 解决方案?

这是一个尚未完成我想要的操作的 codepen,但可以用作为您节省一些时间的起点:http://codepen.io/anon/pen/grBwEp

注意:我知道如何获得1 | 2 | 3

 1 | 3
 -----
   2

通过更改order 属性。但是,我无法为 switch 设置固定断点,因为我不知道内容的宽度,并且内容各不相同...

【问题讨论】:

  • 您可以更改 div 的顺序,例如 1、3、然后 2,以便使用 css 轻松修复
  • @AtifAzad 不,因为如果它们在一行上,它们也将是 1 | 3 | 2。而且我无法根据断点更改顺序,因为我不知道宽度。
  • 查看下面的答案
  • 由于不能使用媒体查询,答案是否定的,没有 CSS Flexbox 解决方案。 CSS 无法检测到溢出来更改顺序。
  • 是的。我已经玩了好几个小时了..只能用 JS 来完成....

标签: html css flexbox


【解决方案1】:

如果您添加 width: 100% 并最后订购 (order: 3),您可以强制第二个孩子 (child2) 位于新行中,如下所示:

.container {
  display: flex;
  flex-wrap: wrap;
}

.container > div {
  text-align: center;
  color: white;
  font-weight: bold;
}

.container > div.child1 {
  width: 150px;
  background-color: red;
  order: 1;
}

.container > div.child2 {
  background-color: blue;
  order: 3;
  width:100%;
}

.container > div.child3 {
  background-color: green;
  order: 2;
}
<div class="container">
  <div class="child1">1 (fixed width)</div>
  <div class="child2">2 (flexes, but minimal width should be the width of the content)</div>
  <div class="child3">3 (width of content)</div>
</div>

【讨论】:

  • 是的,但这是一个固定的解决方案。现在,它不会在两种情况之间切换。而且我不能使用媒体查询,因为我不知道内容的宽度。
【解决方案2】:

您可以只添加一个媒体查询以获取您想要做出反应的尺寸。这里以 600px 宽度为例:

@media (max-width: 600px) {
  .container > div.child1,
  .container > div.child3 {
    flex: 1 0 auto;
    width: auto;
  }
  .container > div.child2 {
    flex-basis: 100%;
    order: 4;
  }
}

这里是您的 Codepen 的分叉版本:http://codepen.io/anon/pen/LNgRKa/left

【讨论】:

  • 我不能使用断点,因为我不知道我必须打破的宽度,因为内容是可变的。
【解决方案3】:

这就是解决方案

<style>
.one, .two {
    width: 33.3%;
    float: left
}
.three {
    width: 33.3%;
    float: right
}
.one {
    background: #999;
}
.two {
    background: #060;
}
.three {
    background: #336;
}
@media (max-width: 768px) {
.two {
    width: 100%;
    float: none;
    clear: both;
}
}
</style>

和 HTML

<div class="one">01</div>
<div class="three">03</div>
<div class="two">02</div>

【讨论】:

  • 你可以玩 div 我只是随机使用百分比宽度
  • OP 希望第一个 div 具有 150 像素的固定宽度,并且没有媒体查询。
  • 使用这个css希望对你有帮助-----> .one, .two { float:left} .three { float:right} .one { background:#999;宽度:150px;} .two { 背景:#060;} .three { 背景:#336;}
猜你喜欢
  • 2015-01-18
  • 2015-11-10
  • 2012-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多