How do I center grid elements that are side by side in CSS Grid?

Issue

I am trying to center two grid elements side by side. I wanted the heading, paragraph and the bottom links to be one grid element and the image to be another one. grid-template-columns: 1fr 2fr; pushed one element up and the other one was pushed down:

.items {
  display: grid;
  grid-template-columns: 1fr 2fr;
  grid-gap: 1.5rem;
}
<main id="about" class="container">
  <div id="cardio" class="items">
    <h2>Program 1</h2>
    <h1><a href="#cardio">Cardio</a></h1>
    <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Quisquam consequuntur exercitationem dolores ut, sunt eius recusandae ad saepe molestias dolorum accusantium consectetur nostrum inventore facilis voluptate rem eveniet tempora repudiandae
      nihil adipisci mollitia minus maxime labore! Eos facere, distinctio, fugit laboriosam voluptas cumque exercitationem maxime vitae reprehenderit omnis accusantium nam.</p>
    <div class="underline"></div>
    <h1><a href="#strength">Strength</a></h1>
    <div class="underline"></div>
    <h1><a href="#flexibility">Flexibility</a></h1>
    <div class="underline"></div>
    <h1><a href="#yoga">Yoga</a></h1>
    <div id="cardio-image">
      <img src="img/Cardio.png" />
    </div>
  </div>
</main>

Solution

Placing your paragraphs etc. in their own container will yield the result you want with the grid auto-placement algorithm. You could solve this with just CSS by explicitly placing children of .items however I think this is the best solution:

.items {
  display: grid;
  grid-template-columns: 1fr 2fr;
  grid-gap: 1.5rem;
}
<main id="about" class="container">
  <div id="cardio" class="items">
    <section>
      <h2>Program 1</h2>
      <h1><a href="#cardio">Cardio</a></h1>
      <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Quisquam consequuntur exercitationem dolores ut, sunt eius recusandae ad saepe molestias dolorum accusantium consectetur nostrum inventore facilis voluptate rem eveniet tempora repudiandae
        nihil adipisci mollitia minus maxime labore! Eos facere, distinctio, fugit laboriosam voluptas cumque exercitationem maxime vitae reprehenderit omnis accusantium nam.</p>
      <div class="underline"></div>
      <h1><a href="#strength">Strength</a></h1>
      <div class="underline"></div>
      <h1><a href="#flexibility">Flexibility</a></h1>
      <div class="underline"></div>
      <h1><a href="#yoga">Yoga</a></h1>
    </section>
    <div id="cardio-image">
      <img src="img/Cardio.png" />
    </div>
  </div>
</main>

Answered By – Zach Jensz

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.