Is there a CSS only solution to make divs equal height in a vertical grid?

人走茶凉 提交于 2020-01-03 11:56:08

问题


I have a .parent div and within that I have an unknown number of .child divs. I need the child divs to be in a vertical grid and all of them need to be equal height. Unfortunately, I can't use javascript for this.

I have tried different combinations of display: inline-block and float: left, but I can't get the children to be the same height.

I am able to achieve same height using display: table-cell but then I run into another problem that the children don't split onto multiple lines if the total width exceeds the container width.

Is there a way to do this with pure css? I only need to support IE10+ if that helps (flexbox?)


回答1:


You can use a wrapping flexbox - see how the heights are auto-adjusted (due to the align-items:stretch property which is default) when the child divs wrap as you resize the window.

* {
  box-sizing: border-box;
}
body {
  margin: 0;
}
.wrapper {
  display: flex;
  flex-flow: row wrap;
}
.wrapper > div {
  border: 1px solid red;
}
<div class="wrapper">
  <div>
    some text here some text here
  </div>

  <div>
    some text here
    <br/>more text here
  </div>

  <div>
    some text here
    <br/>more text here and some more and some more
  </div>

  <div>
    some text here
    <br/>more text here
    <br/>more text here
  </div>

</div>



回答2:


Yes you could use flexbox.

.parent{
    display: flex;
}
.child{
    flex:1;
}



回答3:


You could try using viewport units.

Something like this might work:

.child {
    height: 1vw;
}

This will make the child elements have 1/100 of the viewport width.

To read more about viewport units

Viewport units support



来源:https://stackoverflow.com/questions/40623064/is-there-a-css-only-solution-to-make-divs-equal-height-in-a-vertical-grid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!