Search code examples
htmlbootstrap-5

Why are these elements centered weirdly using Bootstrap5 rows in a card? How can I vertically center them?


Here's an example of what I'm doing here.

<!DOCTYPE html>
<html>
<head>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
<!-- just a spacer -->
  <div class="m-2"></div>
  <div class="container card">
    <div class="row g-1 m-1">
      <div class="col-6" style="align-content:center;">
        Task goes here
      </div>
      <div class="col-3">
        <button class="btn btn-danger w-100">Delete</button>
      </div>
      <div class="col-3">
        <button class="btn btn-success w-100">Complete</button>
      </div>
    <!-- end row -->
    </div>
  <!-- end container (end single task) -->
  </div>
</body>
</html>

The elements in the container are closer to the bottom than the top, which is the opposite of what I was expecting. Wouldn't they automatically go to the top? Does it add extra padding for some reason?

I tried adding the style align-content: center; to the card, though I'm not quite sure what that's supposed to do... align-content and justify-content seem to only work sometimes and I'm not sure I understand them at all. But anyways adding that did nothing at all, and neither did adding justify-content: center;.

By adding margin: 0; to the style of my col-3s it fixed the centering.. But what I still don't understand is WHY.


Solution

  • this is happened because of Gutters g-1 in <div class="row g-1 m-1"> so if you wanna remove the top margin just remove g-1 and your code will be like this

    <!DOCTYPE html>
    <html>
    <head>
      <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    </head>
    <body>
    <!-- just a spacer -->
      <div class="m-2"></div>
      <div class="container card">
        <div class="row m-1">
          <div class="col-6" style="align-content:center;">
            Task goes here
          </div>
          <div class="col-3">
            <button class="btn btn-danger w-100">Delete</button>
          </div>
          <div class="col-3">
            <button class="btn btn-success w-100">Complete</button>
          </div>
        <!-- end row -->
        </div>
      <!-- end container (end single task) -->
      </div>
    </body>
    </html>