Guide to creating space between columns in a CSS grid layout

Is there a way to create a gutter of 20px or 1em for the grid system provided below?

I have managed to align all the divs in a row, but I am looking to insert a space between each div. My goal is to understand how grids function. Check out the code on jsFiddle Here.

body {
    font:20px/1.2 Verdana, Arial; padding:0px; margin:0px;
}

*, *:after, *:before {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing:border-box;
}

.row { width:100%; }

.row > [class*='col-'] { /* ... */ }
.row > [class*='col-']:last-of-type { /* ... */ }

[class*="col-"] {
    float:left; 
    height:200px;
    background-color: #dedede;
    border: 1px solid #000;
    padding-right:20px;
}

[class*=col-]:last-of-type {
    padding-right:0px;
}

.col-1-12 {
    width: calc(100% / 12);
}

.col-2-12 {
    width: calc(100% / 12 * 2);
}

.col-3-12 {
    width: calc(100% / 12 * 3);
}
.col-4-12 {
    width: calc(100% / 12 * 4);
}

HTML:

<div class="row">
    <div class="col-4-12">
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
    </div>
    <div class="col-2-12">
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
    </div>      
    <div class="col-3-12">
        Duis aute irure dolor in reprehenderit in voluptate velit esse
        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </div>  
    <div class="col-3-12">
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
    </div>
</div>

Answer №1

Let's break down the calculation of column widths based on the number of columns and a gutter width of 20px between each column.

For example, take a look at col-2-12:

width: calc( (100% - (12/2 - 1) * 20px) / 12 * 2 );

This formula can be explained as:

width:
    (100%   /* Total width */
      - (12/2 - 1) * 20px /* Number of gutters between col-2  x  gutter width */
    ) / 12 /* Total columns */
      * 2  /* Size of the current column which is col-2 */

Instead of using margin for the first and last columns, you can utilize padding in the container .row and set the margins for those columns to 0.

In addition, since the columns are floated, it's important to clear the float at the bottom of the .row element.

.row {
    padding: 0 20px;
    *zoom: 1;
}

.row:after, .row:before {
    content: ' ';
    display: table;
}

.row:after { clear: both;}

.row > [class*='col-']:first-child { margin-left: 0; }
.row > [class*='col-']:last-child { margin-right: 0; }

See the Working Demo Here.

Sassy CSS

Working with CSS preprocessors like Sass adds a fun twist to creating grid systems!

Here's a Sassy approach to building a fluid grid system:

$total_columns : 12;
$total_width   : 100%;
$gutter_width  : 2%;

.row {
    padding: 0 $gutter_width;
    *zoom: 1;

    &:after, &:before { content: ' '; display: table; }
    &:after { clear: both; }

    & > [class*='col-']:first-child { margin-left: 0; }
    & > [class*='col-']:last-child { margin-right: 0; }
    & > [class*='col-'] { margin: 0 $gutter_width/2; }
}

[class*="col-"] {
    float:left; min-height:200px;
    background-color: #dedede; border: 1px solid #000;
}

@for $i from 1 through $total_columns {
    .col-#{$i}-#{$total_columns} {
        width: (100% - ($total_columns/$i - 1) * $gutter_width) / $total_columns * $i;
    }
}

Check Out the Online Demo Here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for styling a datatable scrollbar with CSS

My preference is to utilize the datatable API when creating tables. $('#datatable-example').dataTable({ "scrollX": true, "info" : false, "fnDrawCallback" : function(oSettings) { $('td').removeClass('sor ...

What is the best way to add a specific class to another class in my CSS code?

Is it possible to apply a CSS class defined in css1.css to another HTML class defined in css2.css? In css1.css: div.classPredefined { border: solid 1px #000; } In css2.css: div.newClass { background: #CCC; /*apply-class: classPredefined;*/ } Although ...

Styling for a music player widget

Over on my blog at , I've added an audio player with a stylish round shape using CSS. It's positioned neatly in the top left corner of the image in the latest post. In my current browser (Firefox 46.0), I'm noticing that the bottom and left ...

Preventing child elements from inheriting properties in a sequential order

Taking a look at this particular demo: http://jsbin.com/teqifogime/edit?html,css,output In the initial section, we observe that the text color changes simultaneously as the background color transitions, owing to inheriting properties from its parent cont ...

Creating a text-only fadein/fadeout carousel using JavaScript with a similar functionality to Bootstrap

Is there a way to create a fade-in/fade-out text only carousel similar to the one on the header of this website using just a few lines of CSS and Javascript instead of including the whole Bootstrap framework? I examined the code of the website and it appe ...

One DataTable cell with a unique feature: two buttons of varying sizes

Currently, I am working with a DataTable that contains a column with two Bootstrap-styled buttons. Strangely, the button on the right appears slightly smaller than the one on the left. Picture illustrating the issue Here is the code snippet: <div cla ...

Creating dynamic animations by shifting the hue of an image on a canvas

Recently, I've been exploring the world of canvas tags and experimenting with drawing images on them. My current project involves creating a fake night/day animation that repeats continuously. After trying various approaches like SVG and CSS3 filters ...

Tips for Embedding External JavaScript and URLs in Joomla Protostar Template

I'm interested in incorporating a hamburger menu into my Joomla protostar template, similar to the one featured on this URL: ['https://codepen.io/PaulVanO/pen/GgGeyE'] This will provide me with a fullscreen hamburger menu for both desktop ...

Prevent HTML escaping inside of a code tag in JavaScript

Is there a way to search for tags "<" and ">" within a <code> block, setting them as text instead of HTML so that all tags and HTML can be displayed on the page? Currently, when I use jQuery to do a string replace, all tags are coming through ...

Ensure an element stays in its position relative to another element by utilizing the CSS property "position: absolute"

I want to incorporate a circle with an image inside into a navbar. The circle should be larger than the navbar, similar to the image shown here: https://i.sstatic.net/kpJgC.png I have been using "position: absolute" to keep the circle in place, but the is ...

Expanding divs automatically depending on the content they contain

Currently, I have been developing a template for a database-driven page that is supposed to contain four divs for content arranged like this: ----- ----- | 1 | | 2 | ----- ----- ----- ----- | 3 | | 4 | ----- ----- The information in each box will always ...

Building a table using a JSON object in a React component

I have been dynamically creating a table in React based on the API response received. data = {"name":"tom", "age":23, "group":null, "phone":xxx} Everything was working fine until I encountered a scenario w ...

Is it expected for every element to return true when checking their visibility with isDisplayed() after performing a get() method

Why are WebDriver get() and isDisplayed() methods not functioning as expected? According to the documentation: This is done using an HTTP GET operation, and the method will block until the load is complete As seen in similar questions such as Wait fo ...

Place icon on the left side of the header one

Is there a way to adjust the icon so that it fits correctly next to my heading? <div style="width:100%;"> <div style="float: left;width:7%;min-width:40px;"> <img src="http://superfood-zentrum.info/wp-content/uploads/2016/03/square.png ...

Ways to guarantee consistent font appearance across all browsers/platforms for PDF display (Cufon, Images, sIFR)

After countless hours delving into various @font-face issues for RTL languages, font-rendering disparities on different browsers, PDF compatibility, and more. My main goal is to achieve CSS-compatible Arabic text (an RTL language) in an HTML document that ...

What can be done to ensure that the a href tag is functioning as clickable?

Having an issue with my HTML and CSS code for a notification dropdown box. I am unable to click the tag, even after attempting to use JavaScript. Can't seem to figure out what's causing this problem. Any advice on how to make the tag clickable? ...

Setting elements relative to a div can be achieved by using CSS positioning properties

I'm currently learning HTML/CSS and facing a challenge in setting elements relative to a container. After reading about the differences between "relative" and "absolute" positioning, I understand that "relative" positions an element relative to where ...

Create a unique web page layout by utilizing divs and spans

Can the design shown in this image be created? https://i.sstatic.net/hsIaQ.png I've tried the code below but it's not functioning properly. Any assistance would be appreciated! The issue is that the Q and A text should be in a box that automati ...

Could anyone provide some insight into the reason behind this occurrence?

I just came across the most peculiar situation I've ever experienced. Check out this unique test page: <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title></title> <script language=javascript> fun ...

Modify the content and display of a stationary div based on vertical positions

I am interested in creating a vertical website that features multiple divs appearing at specific y-points on the page. These divs will contain text and will always be positioned fixed at 20% from the left and about 250px from the top. My goal is to have t ...