Search code examples
csscss-grid

Button directly under first text of left column in a 2-columns grid


How could I place the button directly under the first paragraph on the first column? I know it's caused by the second paragraph being longer but I'd like to avoid the gap.

As I'd like to have the button last on mobile (all stacked), I'm not I can really move it in the HTML.

.text {
    max-width: 600px;
    margin: 0 auto;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-areas: "a b" "c b";
    /* grid-auto-rows: minmax(min-content, max-content); this doesn't work either */
    column-gap: 24px;
}
p:nth-of-type(1) {
    grid-area: "a";
}
p:nth-of-type(2) {
    grid-area: "b";
}
.button {
    grid-area: "c";
    display: inline-flex;
    margin-right: auto;
    justify-content: center;
    align-items: center;
    height: 40px;
    padding: 0 24px;
    text-decoration: none;
    color: white;
    background: gray;
    border-radius: 6px;
}
<div class="text">
    <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Dolore, porro mollitia. Tenetur quibusdam at voluptate aut expedita!</p>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsum, est asperiores maxime id architecto libero commodi, corrupti sit iusto deserunt quos! Ipsa inventore soluta laudantium repellat culpa! Incidunt, quam eos.</p>
    <a href="#" class="button">Click me</a>
</div>

What I get now: enter image description here What I'd like instead: enter image description here


Solution

  • Here is a Mobile First design approach:

    .text {
      max-width: 600px;
      margin: 0 auto;
      display: grid;
      grid-template-columns: 1fr;
      grid-template-areas: "a" "b" "c";
      column-gap: 24px;
    }
    
    p:nth-of-type(1) {
      grid-area: a;
    }
    
    p:nth-of-type(2) {
      grid-area: b;
    }
    
    .button {
      grid-area: c;
      display: inline-flex;
      margin-right: auto;
      justify-content: center;
      align-items: center;
      height: 40px;
      padding: 0 24px;
      text-decoration: none;
      color: white;
      background: gray;
      border-radius: 6px;
    }
    
    
    /* For non-mobile: */
    
    @media (min-width: 500px) {
      .text {
        grid-template-columns: repeat(2, 1fr);
        grid-template-areas: "a b" "c b";
      }
    }
    <div class="text">
      <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Dolore, porro mollitia. Tenetur quibusdam at voluptate aut expedita!</p>
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsum, est asperiores maxime id architecto libero commodi, corrupti sit iusto deserunt quos! Ipsa inventore soluta laudantium repellat culpa! Incidunt, quam eos.</p>
      <a href="#" class="button">Click me</a>
    </div>

    Video screen shot recording showing mobile vs desktop

    Note: Change the width as needed. I set it to 500px specifically for this example as a SO snippet.