如果使用CSS无法将块元素放入宽度为100%的另一行中,怎么办?

时间:2018-12-03 08:41:18

标签: css

我有以下要求:当几个块元素不能排成一排时,将它们放到另一排中并使其宽度为100%(如果它们排成一排,则采用自动宽度)。因此,问题是下一个:是否可以仅使用CSS来实现?非常感谢!

.container {
  width: 300px;
  border: 1px solid grey;
  padding: 10px;
  text-align: center;
  box-sizing: border-box;
}

.box {
  display: inline-block;
  width: 100px;
  height: 50px;
  background-color: gray;
  box-sizing: border-box;
}

.container2 .box {
  width: 100%;
}
if they fit in one row than take auto width
<div class="container">
  <div class="box"></div>
  <div class="box"></div>  
</div>

<br/>
If they don’t fit in one row put<br/>
them into another and make them to be 100% width
<div class="container container2">
  <div class="box"></div>
  <div class="box"></div>  
</div>

1 个答案:

答案 0 :(得分:0)

这是您要实现的目标吗?

在第一行溢出时,使用flex-wrap自动创建新行。

.container {
  display: flex;
  flex-wrap: wrap;
  width: 250px;
  border: 1px solid grey;
  padding: 10px 0 0 10px;
  text-align: center;
  box-sizing: border-box;
}

.box {
  flex: 1 0 100px;
  height: 50px;
  background-color: gray;
  box-sizing: border-box;
  margin: 0 10px 10px 0;
}
<div class="container">
  <div class="box"></div>
</div>

<br/>

<div class="container">
  <div class="box"></div>
  <div class="box"></div>
</div>

<br/>

<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>


对于动态内容

$(".container").each(function() {
  if ($(this).height() > 100) {
    $(".box", this).each(function() {
      $(this).addClass("stretch");
    });
  }
});
.container {
  display: flex;
  flex-wrap: wrap;
  width: 250px;
  border: 1px solid grey;
  padding: 10px 0 0 10px;
  text-align: center;
  box-sizing: border-box;
}

.box {
  height: 50px;
  background-color: gray;
  box-sizing: border-box;
  margin: 0 10px 10px 0;
  padding: 0 10px;
}

.stretch {
  flex: 1 0 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <div class="box">text</div>
</div>

<br/>

<div class="container">
  <div class="box">text</div>
  <div class="box">more text than text</div>
</div>

<br/>

<div class="container">
  <div class="box">text</div>
  <div class="box">more text than text</div>
  <div class="box">Lots more text than more text than text</div>
</div>