Thursday, March 28, 2024

How to Create Multi-columns in CSS3 and JavaScript

This article will show the code that it takes to create CSS3 multi-columns, like those you find in a newspaper, and it will have a bonus: you’ll be able to change the number of columns and the gap in the columns with a click of the mouse. The demo can be found here. The original author of the code is unknown, but he is the Admin on Script-Tutorials.com.

Show Me the HTML!

We’ll start with the HTML. The only note the author states is that the code only has one div element, which is a rather remarkable achievement for code that appears it could have a potential of up to five divs, to account for the total number of columns that you can create. The author’s original text was replaced with lorem ipsum to avoid any distraction the original text might have caused.

<!DOCTYPE html>
<html lang=”en” >
    <head>
        <meta charset=”utf-8″ />
        <title>Multi-columns with CSS3</title>
        <link href=”css/main.css” rel=”stylesheet” type=”text/css” />
        <script type=”text/javascript” src=”js/jquery-1.5.2.min.js”></script>
        <script type=”text/javascript” src=”js/script.js”></script>
    </head>
    <body>
        <div class=”controls”>
            <input type=”button” id=”more_cols” value=”More columns” />
            <input type=”button” id=”less_cols” value=”Less columns” />
            <input type=”button” id=”more_gap” value=”More gap” />
            <input type=”button” id=”less_gap” value=”Less gap” />
        </div>

        <div class=”container” id=”container”>
            <p>”Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 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.”</p>

            <p>”Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 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.”</p>
            <p>”Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?”</p>
        </div>
        </body>
</html>

What About the CSS3 Styles?

The following code shows how to set up the CSS styles:
*{
    margin:0;
    padding:0;
}

body {
    background-color:#bababa;
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
}

footer {
    background-color:#212121;
    bottom:0;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    left:0;
    position:fixed;
    width:100%;
    z-index:100;
}

footer h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}

footer a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}

footer .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

/*new styles*/
.container {
    background:#C5DFF0;
    color:#000;
    margin:20px auto;
    padding:20px;
    position:relative;
    width:800px;

    border-radius:5px;
    -moz-border-radius:5px;
    -webkit-border-radius:5px;

    box-shadow:1px 1px 5px #111111;

    column-count: 3;
    column-gap: 3em;
    column-rule: 1px dashed black;
    -moz-column-count: 3;
    -moz-column-gap: 3em;
    -moz-column-rule: 1px dashed black;
    -webkit-column-count: 3;
    -webkit-column-gap: 3em;
    -webkit-column-rule: 1px dashed black;
}
.controls {
    background:#C5DFF0;
    margin:20px auto;
    padding:20px;
    position:relative;
    width:800px;

    box-shadow:1px 1px 5px #111111;
    border-radius:5px;
    -moz-border-radius:5px;
    -webkit-border-radius:5px;
}
.controls input[type=button] {
    border: 1px solid #000;
    background-color: #666;
    box-shadow: 0 1px 0 rgba(150, 150, 150, 0.5);
    color: #FFF;
    cursor: pointer;
    font-size: 14px;
    font-weight: bold;
    margin-right: 10px;
    padding: 8px 12px;
}
.controls input[type=button]:hover {
    background-color:#444;
}
.controls input[type=button]:active {
    background-color:#000;
}

The Column-Specific Code

There is nothing new or groundbreaking in the above code sample. But for the purposes of this article, and because we are focusing on columns, we will look a bit closer at the column-specific code:

column-count: 3;
column-gap: 3em;
column-rule: 1px dashed black;
-moz-column-count: 3;
-moz-column-gap: 3em;
-moz-column-rule: 1px dashed black;
-webkit-column-count: 3;
-webkit-column-gap: 3em;
-webkit-column-rule: 1px dashed black;

Column-count is defined by the W3C as, “This property describes the number of columns of a multicol element. Auto means that the number of columns will be determined by other properties (e.g., ‘column-width’, if it has a non-auto value). <integer> describes the optimal number of columns into which the content of the element will be flowed. Values must be greater than 0. If both ‘column-width’ and ‘column-count’ have non-auto values, the integer value describes the maximum number of columns.”

The W3C defines column-gap as, “The ‘column-gap’ property sets the gap between columns. If there is a column rule between columns, it will appear in the middle of the gap. The ‘normal’ value is UA-specific. A value of ‘1em’ is suggested. Column gaps cannot be negative.”

This particular example shows vendor-specific code for count, gap and rule along with a generic, non-vendor specific code. It must be assumed that this is a safeguard so that you won’t have to change your code as this code becomes standard for all browsers.

And Now for the JavaScript!

To finish, here’s the JavaScript code so that you can tweak the number of columns and the gap width:

$(function(){
    var iColumns = 3;
    var iGap = 3;
    var cont = document.getElementById(‘container’);

   $(‘#less_cols’).click(function(e) { // mouse click handler
        iColumns–; // decreasing amount of columns
        if (iColumns < 1) iColumns = 1;
        cont.style.MozColumnCount = iColumns; // apply styles
        cont.style.WebkitColumnCount = iColumns;
    });
    $(‘#more_cols’).click(function(e) {
        iColumns++; // increasing amount of columns
        if (iColumns > 5) iColumns = 5;
        cont.style.MozColumnCount = iColumns; // apply styles
        cont.style.WebkitColumnCount = iColumns;
    });
    $(‘#less_gap’).click(function(e) {
        iGap–; // decreasing value of gap
        if (iGap < 0) iGap = 0;
        cont.style.MozColumnGap = iGap+’em’; // apply styles
        cont.style.WebkitColumnGap = iGap+’em’;
    });
    $(‘#more_gap’).click(function(e) {
        iGap++; // increasing value of gap
        if (iGap > 5) iGap = 5;
        cont.style.MozColumnGap = iGap+’em’; // apply styles
        cont.style.WebkitColumnGap = iGap+’em’;
    });
});

I hope you found this CSS3 code useful.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured