How to Remove Space Between Image and Text in HTML?

In this quick post I will show how to remove space between image and text with CSS flexbox.

First let’s look at our starting code.

HTML

<section>
  <img src="rocket.jpg" alt="rocket">
  <h2>Rocket in Space</h2>
</section>

CSS

*{
    box-sizing: border-box;
    padding: 0;
    margin: 0;
}
section{
    width: 400px;
    margin: 0 auto;
}
img{
    width: 100%;
}
h2{
    text-align: center;
    background-color: black;
    color: white;
    padding: 15px;
}

We have given width 100% to image so that it covers the whole width of section element which is set to 400px.

You can see the space/gap between image and text.

space between image and text

Now to remove that space add these two lines of codes in section element.

section{
    width: 400px;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
}
remove space between image and text