James N James N - 3 months ago 23
CSS Question

make a square of 4 individual squares

I am working on a css layout involving 3 pieces. 1 full square w/ image, 1 square with 2 top squares and 1 bottom rectangle, and 1 square w/ 4 individual squares inside the main square. I'm pretty sure I have the first 2 down, but the one I am working on that I am having a problem with is the square w/ 4 squares inside it.

I have something that kind of works, but anything outside of a large viewport collapses. Here is my code, has anyone built something similar?



.test {
width: 100%;
height: auto;
border: 1px solid red;
display: block;
}
.inner {
width: calc(49% + 13px);
display: inline-block;
height: 100px;
margin: 0px -6px 0px 0px;
}
.inner:nth-child(even) {
border: 1px solid blue;
}
.inner:nth-child(odd) {
border: 1px solid green;
}

<div class="test">
<div class="inner">
1
</div>
<div class='inner'>
2
</div>
<div class="inner">
3
</div>
<div class="inner">
4
</div>
</div>




Answer

If you're looking for a 2x2 grid and not using flexbox then I would float instead of inline-block.

* {
  box-sizing: border-box;
}
.test {
  border: 1px solid red;
  overflow: hidden; // clearfix
}
.inner {
  width: 50%;
  float: left;
  height: 100px;
}
.inner:nth-child(even) {
  border: 1px solid blue;
}
.inner:nth-child(odd) {
  border: 1px solid green;
}
<div class="test">
  <div class="inner">
    1
  </div>
  <div class='inner'>
    2
  </div>
  <div class="inner">
    3
  </div>
  <div class="inner">
    4
  </div>
</div>

box-sizing: border-box; allows you to include padding and borders with your width/height declarations. Helpful when padding and borders cause elements to wrap when you don't want them to.