CSS:如何使行中的列适合

时间:2018-07-31 14:17:26

标签: css

我有一些DIV,我需要在2个相等的列中显示它们。如果其中一个DIV大于50%,则所有DIV都应显示在1列中 例如我有这个-jsfiddle.net/w2m0sjav/,我应该显示为-jsfiddle.net/sxmp8bw0/ 如果所有DIV都小于实际值-jsfiddle.net/r4L0g5eb/

#container {
  width: 100%;
  text-align: left;
  display: flex;
  flex-wrap: wrap;
}
#container .item {
    border-style: solid;
    min-width: 40%;
    margin: 10px;
    padding: 10px;
}
<div id="container">
  <div class="item">small answer</div>
  <div class="item">small answer</div>
  <div class="item">very-very-very-very-very-very-very-very-very-very-very-very-very-very-very-very-very-very big answer</div>
  <div class="item">small answer</div>
  <div class="item">small answer</div>
</div>

1 个答案:

答案 0 :(得分:0)

就像评论中已经提到的那样,我认为单独使用CSS不可能做到这一点,但是您可以使用一些JS代码段来做到这一点:

const container = document.getElementById('container');
const items = document.querySelectorAll('#container .item');

const containerHalfWidth = parseInt(getComputedStyle(container).width, 10) / 2;

items.forEach((item) => {
let itemWidth = parseInt(getComputedStyle(item).width, 10);
    if (itemWidth > containerHalfWidth) {
    // try commenting out this line below
    container.classList.add('one-column');
  }
});
#container {
  text-align: left;
  display: flex;
  flex-wrap: wrap;
}

#container .item {
  border-style: solid;
  box-sizing: border-box;
  /* we want the cards to make 2 full columns inside container
     but also have 10px margins on either side of them */
  min-width: calc(50% - 20px);
  margin: 10px;
  padding: 10px;
}

#container.one-column .item {
  width: calc(100% - 20px);
}
<div id="container">
  <div class="item">small answer</div>
  <div class="item">small answer</div>
  <div class="item">very-very-very-very-very-very-very-very-very-very-very-very-very-very-very-very-very-very big answer</div>
  <div class="item">small answer</div>
  <div class="item">small answer</div>
</div>

如果您愿意,还可以使用JSFiddle链接:https://jsfiddle.net/w2m0sjav/29/