Home > Software engineering >  How do I center grid elements that are side by side in CSS Grid?
How do I center grid elements that are side by side in CSS Grid?

Time:06-01

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" >
  <div id="cardio" >
    <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 ></div>
    <h1><a href="#strength">Strength</a></h1>
    <div ></div>
    <h1><a href="#flexibility">Flexibility</a></h1>
    <div ></div>
    <h1><a href="#yoga">Yoga</a></h1>
    <div id="cardio-image">
      <img src="img/Cardio.png" />
    </div>
  </div>
</main>

CodePudding user response:

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" >
  <div id="cardio" >
    <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 ></div>
      <h1><a href="#strength">Strength</a></h1>
      <div ></div>
      <h1><a href="#flexibility">Flexibility</a></h1>
      <div ></div>
      <h1><a href="#yoga">Yoga</a></h1>
    </section>
    <div id="cardio-image">
      <img src="img/Cardio.png" />
    </div>
  </div>
</main>

  • Related