CSS Styling and Centering Images

Centering Images and Using display:block
Images are inline elements by default. Inline images behave like tall text characters and sit inside a line of text. For most layouts, it is easier to treat images as block elements.

Default <img> behavior as inline elements:

This picture is in the middle of the text.

 

<img> as a block element:

Above the image
Below the image

 

Centering an image
Block images can be centered with margin: 0 auto;

<img class="centerpic" src="cat.png">

<style>
.centerpic {
  display: block;
  margin: 0 auto;
  width: 300px;   /* optional but often helpful */
}
</style>

How “margin: 0 auto;” works

This is a shorthand that accepts two numbers:
The first number sets top and bottom margin.
The second number sets left and right margins.

When an element is a block and has an explicit width, the browser knows how wide it is.

Setting left and right margins to auto tells the browser to split the leftover space equally on both sides.

Result: the image is centered without extra tricks.

Why block images are easier
Block elements start on their own line and have a clear rectangular area.
Inline images stay inside text flow, making centering unpredictable unless the parent element is controlled.

Why centering sometimes needs a width
margin: auto works best when the browser knows the width of the block.
If theme CSS or container rules interfere, setting width: gives the browser a firm size to center.

Side-by-side images
Use inline-block when placing multiple images in a row.

<img class="thumb" src="cat.png">
<img class="thumb" src="dog.png">

<style>
.thumb {
  display: inline-block;
  width: 150px;
  margin: 10px;
}
</style>

Inline images for icons
Inline is still useful for small icons inside text.

<p>
Here is an inline icon: <img src="star.png" class="icon"> in the sentence.
</p>

<style>
.icon {
  height: 20px;
  display: inline;   /* default */
}
</style>

 


This page was created by ChatGPT with the guidance, editorial scrutiny, and approval of the human creator of this website.