Search code examples
htmlcsscss-grid

CSS Grid Rows to have different widths


I am having an issue with css grids. I am wondering if it is possible to have different widths for each of my grid rows.

My grid is set up as follows:

.section.section--3 .text {
    display: grid;
    justify-content: center;
    padding: 0 10% 0;
    text-align: center;
}

So I basically want my heading, paragraph and button nested inside my text div to have different widths without using max-width and not fill the entire row. Reason being my button should resize in width dynamically based on the length of the text inside.

my HTML is as follows:

<div class="text">
    <h2 class="text__item item--heading">
        Heading
    </h2>
    <p class="text__item item--paragraph">
        Paragraph
    </p>
    <a href="#" class="text__item item--button button button--primary">
        Button
    </a>
</div>

This image illustrates basically what I want to achieve.

image grid

Thanks.


Solution

  • Yes it is possible, and in so many different ways.

    Let me show one:

    .grid {
      
      display: grid;
      
      grid-template-columns: 20% 60%; /* Column width size here*/
      grid-template-rows: 100px 200px; /* Row height size here*/
      
      grid-column-gap: 10px;
      grid-row-gap: 10px;
    }
    
    .item.a{
      background-color: red;
    }
    
    .item.b{
      background-color: green;
    }
    
    .item.c{
      background-color: blue;
    }
    
    .item.d{
      background-color: yellow;
    }
    <div class="grid">
      <div class="item a"></div>
      <div class="item b"></div>
      <div class="item c"></div>
      <div class="item d"></div>
    </div>

    If you really like CSS Grid Layout and want to learn more about i would recommend you this website here.

    Hope it helps, :)