Search code examples
htmlcsscss-grid

How to create a specific layout arrangement using CSS grid?


I have a simple block of three elements which I am showing in my app as follows 3 items on desktop devices but on small devices eg tablets and phones I want to show this element as follows

enter image description here

Here is my solution in file live demo on jsfidle

.grid-container {
  display: grid;
  grid-template-columns: 1fr 1fr 3fr;
  background-color: #2196F3;
  padding: 10px;
}

.grid-item {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.8);
  padding: 20px;
  font-size: 30px;
  text-align: center;
}

@media (max-width: 544px) {
  .grid-container {
    /* I tried this but the 3rd element not taking the full width */
    grid-template-columns: 1fr 2fr;
  }
}
<h1>Grid Elements</h1>
<div class="grid-container">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">
    3
    <h1>Grid Elements</h1>
    <p>A Grid Layout must have a parent element with the <em>display</em> property set to <em>grid</em> or <em>inline-grid</em>.</p>
  </div>
</div>

How can I achieve this?


Solution

  • Add a grid-column: span 2 rule for the third element, defining it through :nth-child(3). This will stretch this element by two columns. Like this:

    .grid-item:nth-child(3) {
        grid-column: span 2;
    }
    

    .grid-container {
        display: grid;
        grid-template-columns: 1fr 1fr 3fr;
        background-color: #2196f3;
        padding: 10px;
    }
    
    .grid-item {
        background-color: rgba(255, 255, 255, 0.8);
        border: 1px solid rgba(0, 0, 0, 0.8);
        padding: 20px;
        font-size: 30px;
        text-align: center;
    }
    
    @media (max-width: 544px) {
        .grid-container {
            grid-template-columns: 1fr 2fr;
        }
        .grid-item:nth-child(3) {
            grid-column: span 2;
        }
    }
    <h1>Grid Elements</h1>
    
    <div class="grid-container">
        <div class="grid-item">1</div>
        <div class="grid-item">2</div>
        <div class="grid-item">
            3
            <h1>Grid Elements</h1>
            <p>A Grid Layout must have a parent element with the <em>display</em> property set to <em>grid</em> or <em>inline-grid</em>.</p>
        </div>
    </div>