Is this a legal way to vertically + horizontally center images in HTML?

I came across the following technique to vertically center the image inside the div element.

<div> <img src="someimage.png" /> </div> div { position:relative; width:400px; height:300px; border: solid 1px #cccccc; } img { position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; } 

Created a fiddle for this here: http://jsfiddle.net/MryZv/1/

I did not find online tips guiding this technique.

Is there a clause that I don't see? Is it "safe" to use?

+4
source share
1 answer

This method is justified and documented in the CSS 2.1 specification in sections 10.6.4 and 10.6.5 (Absolutely positioned, non-replaced / replaced elements):

http://www.w3.org/TR/CSS2/visudet.html#abs-non-replaced-height

The height of an absolutely positioned element is calculated in accordance with the following restriction:

  'top' + 'margin-top' + 'border-top-width' + 'padding-top' + 'height' + 'padding-bottom' + 'border-bottom-width' + 'margin-bottom' + 'bottom' = height of containing block 

For an image, the height can be set to the internal height of the image, unless you restrict it otherwise.

If margin-top and margin-bottom use the value auto , then these fields are calculated, considering them equal, which allows vertical centering.

Similar logic applies to calculated widths.

If you have large images that can create overflow conditions, this is a method that will work in browsers compatible with CSS 2.1.

+4
source

Source: https://habr.com/ru/post/1484086/


All Articles