Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How height: auto works in HTML and CSS?

Tags:

html

css

height

In CSS and HTML how does height: auto work? What do browsers consider while calculating height of the element, for which height is set to auto?

like image 229
Debiprasad Avatar asked Sep 06 '13 09:09

Debiprasad


2 Answers

Here's an excerpt on this copied from the W3C CSS2 spec

If it only has inline-level children, the height is the distance between the top of the topmost line box and the bottom of the bottommost line box.

If it has block-level children, the height is the distance between the top margin-edge of the topmost block-level child box and the bottom margin-edge of the bottommost block-level child box.

Absolutely positioned children are ignored, and relatively positioned boxes are considered without their offset. Note that the child box may be an anonymous block box.

In addition, if the element has any floating descendants whose bottom margin edge is below the element's bottom content edge, then the height is increased to include those edges. Only floats that participate in this block formatting context are taken into account, e.g., floats inside absolutely positioned descendants or other floats are not.

like image 144
tom-19 Avatar answered Oct 12 '22 07:10

tom-19


You can split two cases:

  • div and other containers: the height is the one the browser will use if you don't specify anything, trying to contain the element contents. (read Mathijs's answer for more details)
  • images and other block elements with intrinsic dimensions (width and height): if you specify the width, then "height: auto" will scale proportionally.

So, in other words, is useless unless you need to reset the browser behaviour or keep proportions to some objects.

like image 4
Ludovico Grossi Avatar answered Oct 12 '22 07:10

Ludovico Grossi