user1842633 user1842633 - 3 months ago 7
CSS Question

How to center image while also aligning text to the right of image?

I'm trying to align an image in the center of the page while also aligning some text to the right of the image. How would I do this in either css or html?

Here is my current attempt at this:



.center-img {
display: inline-block;
margin: 0 auto;
}

.center-txt {
display: inline-block;
}

<img src="http://placehold.it/350x150" class="center-img"/>
<div class="center-txt">
<h1>Home</h1>
</div>





Right now the image is not centered and the text is not centered vertically with the image

Here is a visual representation of what I would like it to look like in the end:

enter image description here

Answer

Solution 1:

You can use a div to wrap the image and the text in and use text-align: center along with vertical-align: middle.

.center-img,
.center-txt {
  display: inline-block;
  vertical-align: middle;
}
#wrapper {
  text-align: center;
  border: 1px solid red;
}
<div id="wrapper">
  <img src="http://placehold.it/100x100" class="center-img" />
  <div class="center-txt">
    <h1>Home</h1>
  </div>
</div>


Solution 2:

Alternatively, you can use a div to wrap the image and the text in and use flexbox. Use justify-content to center your elements horizontally and align-items: center to align them vertically.

.center-img,
.center-txt {
  display: inline-block;
}
#wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid red;
}
<div id="wrapper">
  <img src="http://placehold.it/100x100" class="center-img" />
  <div class="center-txt">
    <h1>Home</h1>
  </div>
</div>


Now to center the above wrapper to the middle of the screen you can use:

#wrapper {
   position: fixed;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
}

Example:

.center-img,
.center-txt {
  display: inline-block;
}
#wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid red;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div id="wrapper">
  <img src="http://placehold.it/100x100" class="center-img" />
  <div class="center-txt">
    <h1>Home</h1>
  </div>
</div>