ESX ESX - 2 months ago 12
CSS Question

CSS two columns 100% width with same height (a square)

Hi i'm trying to create a gridview with two columns with square elements (same width same height dinanicaly,height depend on the width of screen) .This is a working example but the two columns dont cover all the width. Any idea how to do this?



.container{
display: inline-block;
width: 100%;
background-color: #0ff;
}

box {
background:pink;
margin:2px;
float:left;
width:40vw;
height: 40vw;
}

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




Answer

When you use width: 40vw;, they take 40% of the window's width which is 80% each row, so it is expected to leaving another 20% is blank.

What you need is using a width: 50%; that makes 2 boxes will fill the full 100%, but since they are also having a margin: 2px, so you may have to minus 4px from 50% (2px for margin-left and 2px for margin-right). So that should be width: calc(50% - 4px); and beside using a viewpoint unit vw in height, I suggest you could use the padding-bottom: calc(50% - 4px); which will makes the boxes' height same as their width:

box {
    background:pink;
    margin:2px;
    float:left;
    width: calc(50% - 4px);
    padding-bottom: calc(50% - 4px)
}

Working JsFiddle: https://jsfiddle.net/v8bdmLse/