DEV Community

webstuff
webstuff

Posted on

Different ways of creating columns using css

So here's a 5 minute read on this thing.
i know it's not that interesting, but sometimes you need to get back to basics, if you don't know the basics you kinda struggle with advanced stuff.
So... here's my take on creating columns or making grids in css.

  1. the display: inline-block approach The idea is that the wrapper has some white-space that you need to remove. Then by using box-sizing you make the elements align better. you don't need the float, because inline-block will do it for you. the Html is as follows:
<div class="columns_container">
    <div class="col col2">column 1</div>
    <div class="col col2">column 2</div>
</div>
Enter fullscreen mode Exit fullscreen mode

The CSS is like so:

.columns_container {
        display: block;
        max-width: 1200px;
        white-space: nowrap;
        font-size: 0;
        padding: 15px;
    background: gray;
    }

    .columns_container .col {
        display: inline-block;
        vertical-align: middle;
        box-sizing: border-box;
        white-space: normal;
        font-size: 18px;
    }

    .columns_container .col.col2 {
        width: 50%;
    }
Enter fullscreen mode Exit fullscreen mode
  1. the display: flex approach ( this one is popular now a days ) the HTML structure is as follows
<div class="columns_container_flex">
    <div class="col col2">column 1</div>
    <div class="col col2">column 2</div>
</div>
Enter fullscreen mode Exit fullscreen mode

The Css part

.columns_container_flex {
                    max-width: 1200px;
                    display: flex;
                    flex-flow: row wrap;
                    padding: 15px;
                    background: #d8d8d8;
                }

                .columns_container_flex .col {
                    flex: 0 0 100%;

                }

                .columns_container_flex .col.col2 {
                    flex: 0 0 50%;
                }

Enter fullscreen mode Exit fullscreen mode
  1. the display grid approach Now this one is more for the future, but people online say it should be used with display flex, so that you create the wrapper with grid and you arange the content with display: flex

The Html:

<div class="columns_container_grid">
    <div class="col col2">column 1</div>
    <div class="col col2">column 2</div>
</div>
Enter fullscreen mode Exit fullscreen mode

The css:

.columns_container_grid {
        max-width: 1200px;
        display: grid;
        grid-template-columns: 50% 50%;
        background-color: #2196F3;
        padding: 15px;
    }

Enter fullscreen mode Exit fullscreen mode

That's my tale on this subject, hope it helped you guys.
Have a great day!

Top comments (0)