Explain Codes LogoExplain Codes Logo

Is <img> element block level or inline level?

html
responsive-design
css
best-practices
Alex KataevbyAlex Kataev·Dec 23, 2024
TLDR

By default, the <img> element is inline, "whispering sweet nothings" to your text. Wanna stand it alone?

img { display: block; // .block "You complete me" said <img> to content around. }

Though, truth be told, an <img> behaves mostly like an inline-block, considering the "special" width and height attributes it can possess. I bet you can relate to that!

Inline or inline-block: That’s the question!

By nature, an <img> element plays well with other elements, cozying up like an inline element:

  • Mixes well: they mingle and maintain the flow of text—kinda like that extroverted friend we all love and hate.
  • Doesn't take up space: no new lines here; we're not ending a paragraph.
  • Only sideways please: Top or bottom margins? Nah... [margin: 0 auto;] always gives her the center stage though.

But hey, <img> can be a blockhead too! Simply flex your CSS muscles and apply:

img.inline-block { display: inline-block; // .inline-block "You can't flame me, I hop around." }

Now she’s a block-level celebrity—a diva with width, height and the margins to match. But unlike her block-level sisters, she sticks with her crowd... like a groupie.

Styling: Dressing up the <img>

✍️ Join me for the dressing up party:

  • Width 101: No space? No problem. Use max-width: 100%, height: auto for fitting into those skinny jeans.
img.responsive { max-width: 100%; height: auto; // .auto "One size fits all. No crash diets needed." }
  • Getting centered: give <img> angel wings with display:block and margin:auto.
img.center { display: block; margin: auto; // auto "Center of the universe, that's me!" }
  • Float around: Let <img> freestyle rap and float with float:left/right.
img.left { float: left; margin-right: 20px; // .left "Look ma, I can float!" } img.right { float: right; margin-left: 20px; // .right "I can float too, but a bit to the right." }
  • Framed!: Snap some CSS paparazzi-baiting, border-grabbing frame to <img>.
img.framed { border: 5px solid #333; padding: 4px; // .framed "Just put me in a frame, already!" }

Good practices: Images on a diet and alt for air

Some practical tips for a fit and healthy <img>:

  • Staying responsive: Grip the curves of your images with max-width and height:auto.
  • Breathing easy: Spare a thought for assistive technology users; an aptly filled alt text can be their oxygen mask.
  • Caption that: Use <figcaption> in combination with <figure> for complete, semantic, caption-friendly images—your <img> now has a voice (and a context!).

Arranging display in the wardrobe

Maintaining a neat wardrobe of CSS classes totted up for <img> display properties means pic styling is a walk in the park:

img.rounded { border-radius: 50%; // .rounded "Look, I'm round. And I'm not self-conscious about it." display: inline-block; }