zac
zac

Reputation: 4898

How to center an image in CSS Grid?

How I can make the image to be centered vertically on the left and the text on the right ?

.pricing1box {
  display: grid;
  grid-template-columns: repeat(auto-fit, 300px);
  color: #444;
  margin-top: 150px;
  justify-content: center;
}

.pricing1box-div {
  background-color: orange;
  color: #fff;
  border-radius: 5px;
  font-size: 150%;
}
<div class="pricing1box">
  <div class="pricing1box-div">
    <img src="http://placehold.it/350x150.png" style="float: left; display: inline-block; width: 100px; vertical-align: middle;">
    <h6 style="color: black; padding: 10px;">Title</h6>
    <p style="font: 10px blue;">Powered by me</p>
    <br>
    <p>A dgdfg dfgdhdgfh fdgh dhdfg wertdfg dfgdh ergdfgd egr dfgdhd hdfh </p>
  </div>
</div>

Upvotes: 5

Views: 38630

Answers (3)

Michael Benjamin
Michael Benjamin

Reputation: 371223

You can use grid properties on the image and text, as well. Just make the parent a grid container.

.pricing1box {
  display: grid;
  grid-template-columns: repeat(auto-fit, 300px);
  justify-content: center;  
  color: #444;
}

.pricing1box-div {
  display: grid;         /* new; nested grid container */
  grid-template-columns: 1fr 1fr;
  grid-template-rows: auto auto auto;
  background-color: orange;
  color: #fff;
  border-radius: 5px;
  font-size: 150%;
}

.pricing1box-div img {
  grid-column: 1;
  grid-row: 1 / -1;      /* from first line at start, to first line at end */
  align-self: center;    /* vertical centering */
  width: 100px;
}

.pricing1box-div :not(img) {
  grid-column: 2;
}
<div class="pricing1box">
  <div class="pricing1box-div">
    <img src="http://placehold.it/350x150.png">
    <h6 style="color: black; padding: 10px;">Title</h6>
    <p style="font: 10px blue;">Powered by me</p>
    <p>A dgdfg dfgdhdgfh fdgh dhdfg wertdfg dfgdh ergdfgd egr dfgdhd hdfh </p>
  </div>
</div>

Upvotes: 2

GuCier
GuCier

Reputation: 7415

You can also mix flex & grid for readability

body {
  display: grid;
  grid-template-columns: repeat(auto-fit, 300px);
  justify-content: center;
  align-content: bottom;
}

div {
  display:flex;
  align-items: center; /* Vertical center of image & text */
  background-color: orange;
}

p {
  padding: 100px 10px; /* Demo stuff */
}
<div>
  <img src="//placecage.com/100/100">
  <p>text here</p>
</div>

Upvotes: 2

Jim VanPetten
Jim VanPetten

Reputation: 436

Try this:

  position: relative;
  top: 50%;
  transform: translateY(-50%);

or maybe you just need this: align="middle"

<img src="http://placehold.it/350x150.png" align="middle" style="float: left; display: inline-block; width: 100px; vertical-align: middle;">

Upvotes: 0

Related Questions