【问题标题】:Why does width:auto behave differently than height:auto?为什么 width:auto 的行为与 height:auto 不同?
【发布时间】:2016-05-02 00:57:58
【问题描述】:

我没有得到auto 的值。如果应用于height,它将采用孩子的高度,但如果应用于width,它将采用父母的宽度。

auto 值本身没有 MDN 帖子,Google 产生“100% VS auto”命中而不是“width:auto VS height:auto”命中。

对于我目前的需求,我希望将一个元素扩展到其子元素的宽度,但总的来说,我想知道auto 的处理方式。

 .divXS {
   width: 100px;
   height: 100px;
   background: green;
 }
 
 .divXXS {
   width: 50px;
   height: 50px;
   background: yellow;
 }
 
 .divSM {
   width: 200px;
   height: 200px;
 }
 
 #Father {
   background: blue;
   border: 3px solid #20295E;
 }
 
 #Mother {
   background: pink;
   border: 3px solid #DB6DBE;
 }
 
 #Daughter {
   width: 100%;
   height: 100%;
 }
 
 #Son {
   width: auto;
   height: auto;
 }
<div class="divSM" id="Mother">
  <div class="divXS" id="Daughter">
    <div class="divXXS" id="grandDaughter"></div>
  </div>
</div>

<div class="divSM" id="Father">
  <div class="divXS" id="Son">
    <div class="divXXS" id="grandSon"></div>
  </div>
</div>

jsFiddle/jsBin

【问题讨论】:

  • "没有关于 auto 属性本身的 MDN 帖子" 那是因为 auto 不是属性,它是一个值,它不是像 initial 或 inherit 那样的 CSS 范围的关键字,它的行为不同对于不同的属性 - for a reason.
  • “我想要一个元素扩展到其子元素的宽度”您可以通过将父元素设为inline-block 来实现这一点,然后它将适应其子元素。

标签: html css


【解决方案1】:

'auto' 对于 width 属性和 height 属性的行为甚至并不总是相同。 width 属性可以有不同的行为,不仅取决于元素的显示类型,还取决于 same 显示类型的 other 属性的值。这就是为什么它被称为“自动”——来自我的回答 here

根据元素的内容或上下文,自动调整该属性的值。

根据您的描述,我假设您的问题是在块布局的上下文中。块布局由一系列以正常流程垂直堆叠的块级框组成。

因此,默认情况下,块容器盒只需长到足以容纳垂直堆叠的后代。而且由于块级盒子在正常流程中从不水平堆叠,因此它们没有理由不能伸展到包含块的全宽。 (它们甚至不需要缩小以适应相同块格式化上下文中的浮点数,尽管它们内部的 行框 可以,但这完全是一个单独的主题。)

这就是为什么在块布局中,自动高度基于后代的总高度,而自动宽度基于包含块的宽度。

【讨论】:

    猜你喜欢
    • 2019-11-01
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    相关资源
    最近更新 更多