【问题标题】:Why does text-decoration stop inheriting based on the positioning of the child element?为什么 text-decoration 会根据子元素的定位停止继承?
【发布时间】:2016-09-14 12:55:33
【问题描述】:

如果我有父 div 和子 div,并且我在父 div 上设置了 text-decoration:underline,这将适用于子 div 的文本内容。但是,如果我将子 div 设置为 position:absoluteposition:fixed,则不再继承文本装饰。

我查看了规范,但没有看到任何描述这一点的内容。还有大多数地方,例如MDN,将text-decorationtext-decoration-line 描述为继承,这让我想知道它为什么会起作用。也就是说,这种行为似乎在所有浏览器中都是一致的,所以我认为我遗漏了一些东西。

查看下面的代码sn-p,您可以在其中使用按钮更改子div的位置css:

var positions = ['static','relative','fixed', 'absolute']


for(idx in positions){
    $('#buttons').append($('<input/>').prop('type','button').prop('value',positions[idx]))
}

$('input').click(function(){
    $('#child').css('position',this.value);
})
#parent{
  text-decoration:underline;
}
#buttons{
  position:absolute;
  top:30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
  <div id="child">
    Sample
  </div>
</div>

<div id="buttons"/>

【问题讨论】:

    标签: html css inheritance text-decorations


    【解决方案1】:

    没错,文本装饰是继承的。这种特殊行为与继承的 CSS 定义(这是cascade 的一部分)有些不同。该规范专门使用“传播”一词来描述文本装饰的行为,相反与级联无关。特别是it says

    请注意,文本装饰不会传播到浮动和绝对定位的后代

    就本声明而言,固定定位框和绝对定位框都被视为绝对定位。

    文本装饰的传播和继承之间的主要区别在于,通过继承,后代实际上会为自己获取父级的 CSS 属性。文本装饰不是这种情况——绘制在后代上的装饰实际上是父级的装饰。您可以通过为父元素和子元素赋予不同的前景色来看到这一点:

    var positions = ['static','relative','fixed', 'absolute']
    
    
    for(idx in positions){
        $('#buttons').append($('<input/>').prop('type','button').prop('value',positions[idx]))
    }
    
    $('input').click(function(){
        $('#child').css('position',this.value);
    })
    #parent{
      text-decoration:underline;
      color:red;
    }
    #child{
      color:blue;
    }
    #buttons{
      position:absolute;
      top:30px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="parent">
      <div id="child">
        Sample
      </div>
    </div>
    
    <div id="buttons"></div>

    我对@9​​87654323@ 的回答探讨了inherit 关键字如何影响——或者更确切地说,影响——文本装饰是否传播到某些后代。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      • 2020-10-21
      • 2014-02-25
      相关资源
      最近更新 更多