Is <img>
element block level or inline level?
By default, the <img>
element is inline, "whispering sweet nothings" to your text. Wanna stand it alone?
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:
Now she’s a block-level celebrity—a diva with width, height and the margin
s 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.
- Getting centered: give
<img>
angel wings withdisplay:block
andmargin:auto
.
- Float around: Let
<img>
freestyle rap and float withfloat:left/right
.
- Framed!: Snap some CSS paparazzi-baiting, border-grabbing frame to
<img>
.
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
andheight: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:
Was this article helpful?