Geeky Geeky - 2 months ago 7
CSS Question

How can we make a 4 by 4 grid using css

I am trying to make a 4 by 4 grid using css and html.

Here is the link to my code:
http://jsbin.com/wawebaquga/edit?html,css,js,output

Please let me know if i have done correctly.
If not, can you please let me know what is right process to follow.

PS:Forgot to add sample screenshot. Here is the link to it
http://etc.usf.edu/clipart/42600/42668/grid_42668.htm

Following is the code/mark up:

<div id="container">
<div class="box">c-1
<p class="contents"></p>
</div>
<div class="box">c-2

<p class="contents"></p>
</div>
<div class="box">c-3

<p class="contents"></p>
</div>
<div class="box">c-4

<p class="contents"></p>
</div>

<div class="box">c-5

<p class="contents"></p>
</div>
<div class="box">c-6

<p class="contents"></p>
</div>
<div class="box">c-7

<p class="contents"></p>
</div>
<div class="box">c-8

<p class="contents"></p>
</div>

<div class="box">c-9

<p class="contents"></p>
</div>
<div class="box">c-10

<p class="contents"></p>
</div>
<div class="box">c-11

<p class="contents"></p>
</div>
<div class="box">c-12

<p class="contents"></p>
</div>

<div class="box">c-13

<p class="contents"></p>
</div>
<div class="box">c-14

<p class="contents"></p>
</div>
<div class="box">c-15

<p class="contents"></p>
</div>
<div class="box">c-16

<p class="contents"></p>
</div>
</div>


CSS:

#container {
width: 300px;
column-count: 4;
background: green;
border: 1px solid;
column-rule:1px solid;

}

.box {
color: blue;
border-bottom:1px solid;

}

.box .contents{
visibility: hidden;
width:100px;

}


Thanks

Answer

That wouldn't work, no. Look at flex-box or float-right for a grid-type arrangement of div elements. Flexbox is especially powerful, really just need 2-3 lines of CSS to accomplish this:

* { box-sizing: border-box; }
#container { width: 100%; display: flex; flex-direction: row; flex-wrap: wrap; background: green; }

#container > div { width: 25%; height: 25vw; border: white 1px solid; }

What's happening:

box-sizing - depending on what browser you're on, the 1px border will add to the overall width and break the grid (example: 25% of 100px box is 25px, but if your box sizing is off, the border can cause the box to "bloat" to 27px. If each box is 27px, one of the boxes is knocked down to the next row bc there's no space left on the row above it).

By setting it to border-box, it means we're including the border when specifying the DOM's width.

width and height: 25% works for width but not height, so we specify the height with the vw measurement. Be careful with this unit, it's not supported by current version -1 (thanks IE).

flex-everything Neat way to approach modern CSS layout. There are a lot of bells and whistles, but generally speaking I think the rules I used above are pretty self-explanatory. I'm happy to provide any clarification in the comments.

https://jsfiddle.net/z_herring/cg71okst/

Comments