Home > Net >  How do I center <h2> and <img> elements that are inline-block?
How do I center <h2> and <img> elements that are inline-block?

Time:01-29

I am trying to align h2 and img (icon) elements and I know that I should add display: inline-block but they shifted to the left of the section. How can I center them?

HTML:

<h2>Coffee</h2>
<img src="https://cdn.freecodecamp.org/curriculum/css-cafe/coffee.jpg" alt="coffee icon"/>

CSS:

img {
  display: inline-block;
  vertical-align: -8px;
}

h2 {
  display: inline-block;
  text-align: center;
}

Screenshot

CodePudding user response:

Put them in container which is styled text-align: center;:

img {
  display: inline-block;
  vertical-align: -8px;
}

h2 {
  display: inline-block;
  text-align: center;
}

div {
    text-align: center;
}
<div>
  <h2>Coffee</h2>
  <img src="https://cdn.freecodecamp.org/curriculum/css-cafe/coffee.jpg" alt="coffee icon"/>
</div>

CodePudding user response:

Use a <div> to center everything inside (text and image) using text-align:

<style>
div
{
    text-align: center;
}
</style>

<div>
  <h2>Coffee</h2>
  <img src="https://cdn.freecodecamp.org/curriculum/css-cafe/coffee.jpg" alt="coffee icon"/>
</div>

CodePudding user response:

use in parent of image and h2

display: flex;
justify-content: center;
align-items: center;
  • Related