0

So I'm trying to center my image and my button which is in the first and last div of my container-1 div. Howvever it doesn't seem to want to center and I don't understand why. I'd love to know why it's not centering and how to center it peoperly.

.container-1 {
  display: flex;
}

.container-1 div {
  border: 1px #ccc solid;
  padding: 10px;
}

.container-1 .body {
  flex-grow: 1
}

.container-1 .box-img img {
  align-items: center;
  height: 75px;
}

.container-1 .box-button button {
  align-self: center;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-1">

  <div class="box-img">
    <img src="https://images.squarespace-cdn.com/content/5c2aec4b1137a6d8849debf1/1589482673361-JFOXBM38XYSJQ9MUBEDW/image-asset.jpeg?format=1000w&content-type=image%2Fjpeg" />
  </div>

  <div class="body">
    <h3>Title</h3>
    <p>Description</p>
  </div>

  <div class="box-button">
    <button class="btn btn-primary">Button</button>
  </div>

</div>
Riley Varga
  • 670
  • 1
  • 5
  • 15

1 Answers1

2

Basically, you want to use:

display: flex;
align-items: center;

On a parent element. That will vertically center the children.

Have a look - working code below.

.container-1 {
  display: flex;
}

.container-1 div {
  border: 1px #ccc solid;
  padding: 10px;
}

.container-1 .body {
  flex-grow: 1
}

.box-img {
  display: flex;
  align-items: center;
}
.box-img img {
  height: 75px;
}

.box-button {
  display: flex;
  align-items: center;
  
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-1">

  <div class="box-img">
    <img src="https://images.squarespace-cdn.com/content/5c2aec4b1137a6d8849debf1/1589482673361-JFOXBM38XYSJQ9MUBEDW/image-asset.jpeg?format=1000w&content-type=image%2Fjpeg" />
  </div>

  <div class="body">
    <h3>Title</h3>
    <p>Description</p>
  </div>

  <div class="box-button">
    <button class="btn btn-primary">Button</button>
  </div>

</div>
Jakub A Suplicki
  • 4,586
  • 1
  • 23
  • 31
  • I thought having `display: flex;` on the parent would be enough, or I guess container-1 isnt the parent but an ancestor? – Riley Varga Jun 20 '20 at 01:20
  • `display: flex` works on direct children right next to the parent so `display: flex` on ".container-1" flexes in this case containers: ".box-img", ".body" and ".box-button" (not what is inside each of them yet). What you want to do is to use `display: flex` again on what is inside ".box-button", for example. After that, you add `align-items: center;` to center vertically direct children of that container. I hope it clarifies. – Jakub A Suplicki Jun 20 '20 at 01:42