Search code examples
htmlcsscss-grid

How to center items in a div (CSS) in a grid (justify-content and align-items not working)


I have a div with grid layout, with several divs inside. I want the divs inside the grid to be full-height, and I want the content of the divs inside the grid to be centered vertically. I already looked all over the place for a solution, but found none that worked. So far, I've tried using the justify-content and align-items, but they are not doing what I want.

This is what I've tried:

.wrapper {
  display: flex;
  flex-direction: row;
}

.card {
  background-color: beige;
  border: 1px solid rgb(148, 148, 109);
  border-radius: 5%;
  padding: 10px 15px;
  box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.2);
  justify-content: center;
  align-items: center;
}

.one {
  flex: 1;
}

.two {
  flex: 1;
  justify-content: center;
  align-items: center;
  vertical-align: center;
}
<div class="wrapper">
  <div class="card one">
    <h2>Card 1</h2>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Laborum nihil, facere voluptas, amet ipsam, deleniti ullam dolores labore illum cumque praesentium perferendis accusantium. Aspernatur commodi, beatae culpa vel similique sequi.</p>
    <h4>Item 3 just for content.</h4>
  </div>
  <div class="card two">
    <h2>Card 2</h2>
    <p>I want the above heading and this text to be vertically centered on this card (justify-content and align-items doesn't work...</p>
  </div>
</div>

Any input is greatly appreciated!

Thanks! :)


Solution

  • If I am not mistaken it should be so. Just on the "card" class:

    display: flex; align-items: center;

    Adding a div inside will put it in the center.

    .wrapper {
      display: flex;
      flex-direction: row;
    }
    
    .card {
      background-color: beige;
      border: 1px solid rgb(148, 148, 109);
      border-radius: 5%;
      padding: 10px 15px;
      box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.2);
      flex: 1;
      display: flex;
      align-items: center;
    }
    <div class="wrapper">
      <div class="card">
        <div class="inside">
          <h2>Card 1</h2>
          <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Laborum nihil, facere voluptas, amet ipsam, deleniti ullam dolores labore illum cumque praesentium perferendis accusantium. Aspernatur commodi, beatae culpa vel similique sequi.</p>
          <h4>Item 3 just for content.</h4>
        </div>
      </div>
      <div class="card">
        <div class="inside">
          <h2>Card 2</h2>
          <p>I want the above heading and this text to be vertically centered on this card (justify-content and align-items doesn't work...</p>
        </div>
      </div>
    </div>