-1

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

3 Answers3

-1

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>
user1314836
  • 219
  • 1
  • 4
  • 14
-1

You can wrap both h2 and img tags in parent div so you can apply flexbox property easily and center both element.

div{
  display:flex;
  justify-content:center;
  align-items:center;
}
div img{
  margin-left:10px;
}
<div>
  <h2>Coffee</h2>
<img src="https://cdn.freecodecamp.org/curriculum/css-cafe/coffee.jpg" alt="coffee icon"/>
</div>
Yash porwal
  • 301
  • 3
  • 9
-1

To center the text "Coffee" and the cup image inside a section as shown in the screenshot, you can add text-align: center to the <section> element in CSS. This will align all elements inside the section to the center.

section {
  text-align: center;
}

Making <h2> as inline-block, the width become the length of the text "Coffee". Therefore, text-align: center doesn't work.