• Post category:CSS

Easy Way to Create 2 Equal Columns in CSS Grid Layout

CSS Grid 2 Columns

In this article, we will see about how to create 2 columns grid in CSS. To create 2 grid columns, we need to create a grid layout. For that, we need to create a container and create items inside it. Let’s see an example:

Example to create grid layout:

HTML:

<div id="container">
   <div class="item item-1">Item 1</div>
   <div class="item item-2">Item 2</div>
   <div class="item item-3">Item 3</div>
   <div class="item item-4">Item 4</div>
</div>

CSS:

#container{
  border: 2px black solid; 
  display: grid;
}
.item{
   padding: 1px;
   text-align: center;
}
.item-1{
   background-color: red;
}
.item-2{
   background-color: green;
}
.item-3{
   background-color: orange;
}
.item-4{
   background-color: darkviolet;
}

Output:

 css grid 2 columns

Steps:

    1. In the above code, we have created a <div> container and created 4 items inside it in HTML.
      Then in CSS, we set the border and set ‘display’ to ‘grid’ for the container. And then we set the background color for separate items.
    2. If you want to explicitly set a grid by creating columns, you need to make use of the ‘grid-template-columns’ property. The ‘grid-template-columns’ specifies the number of columns in a grid layout. We can give value as a space-separated list, where each value species is the size of the respective column. For ex, if we set the value as “100px 20px”, it will create 2 columns in the grid. The 1st column width is 100px and the 2nd column width is 200px.
      #container{
        border: 2px black solid;
        display: grid;
        grid-template-columns: 100px 200px;
      }
    3.  css grid 2 columnsSee the above output, there is a lot of space on the right side of the container. So, we set the value in pixels for the ‘grid-template-columns’ property. Instead of pixels, we can set by fr (fraction). If you set the value in ‘fr’, it will divide the columns perfectly. To create 2 grid columns, we need to set the CSS ”grid-template-columns property to ‘1fr 1fr’.
      #container{
        border: 2px black solid; 
        display: grid;
        grid-template-columns: 1fr 1fr;
      }

css grid 2 columnsNow see the output, our expected result is displayed successfully. If we have 100% width, column 1 and column 2 take up 50% of the space. So, you should give the value of ‘fr’.

READ ALSO  Good Example to Understand Why CSS Flexbox align-self ?

 

Leave a Reply