Software Engineering

Aligning images using CSS

I’ve always had problems with aligning images using CSS, but with some help of friend I found some easy and elegant solutions that will work in most cases.

How to align an image horizontally inside a block element?
  • Make sure the block element’s width is bigger than the image width, otherwise you might want to align the block element rather than the image.
  • Give the parent block element: text-align: center;

 

How to align an image vertically within (a line of) text?

Either the text or the image will automatically change the line-height, so all will look fine.

  • Don’t touch line-height, unless you want to change the line-height for the text.
  • Give image: vertical-align: middle;

 

How to align an image vertically inside a block element?

This is a little more tricky, but can be done by setting the line height.

  • Give block a fixed height (no percentage) and line-height.
  • Make sure the line-height is equal to the image height.
  • Give image: vertical-align: middle;

 

Why do images behave like this?

HTML elements are either block level elements (<div>, <h1>, <p>, etc.), inline elements (<a>, <span>, <em>, etc.) or replaced elements or inline blocks (<img>, <input>, <select>, etc.).

 

The difference between those elements, according to StackOverflow:

Inline elements:

  • Respect left & right margins and padding, but not top & bottom;
  • Cannot have a width and height set;
  • Allow other elements to sit to their left and right.

Block elements:

  • Respect all of those;
  • Force a line break after the block element.

Inline-block elements:

  • Allow other elements to sit to their left and right;
  • Respect top & bottom margins and padding;
  • Respect height and width.

 

Some more information on line-height can be found here:

Previous Post Next Post

You Might Also Like

No Comments

Leave a Reply