简体   繁体   English

高度如何:自动在HTML和CSS中工作?

[英]How height: auto works in HTML and CSS?

In CSS and HTML how does height: auto work? 在CSS和HTML中, height: auto如何工作? What do browsers consider while calculating height of the element, for which height is set to auto ? 浏览器在计算元素的height (将height设置为auto什么?

Here's an excerpt on this copied from the W3C CSS2 spec 这是摘自W3C CSS2规范的摘录

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, eg, floats inside absolutely positioned descendants or other floats are not. 仅考虑参与此块格式化上下文的浮点数,例如,绝对定位后代内的浮点数或其他浮点数均不考虑在内。

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. div和其他容器 :如果您未指定任何内容(试图包含元素内容),则高度是浏览器将使用的高度。 (read Mathijs's answer for more details) (有关更多详细信息,请阅读Mathijs的答案)
  • 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. 因此,换句话说,除非您需要重置浏览器行为或对某些对象保持比例,否则它是没有用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM