CSS: 子元素display:inline-block的删除线不起作用

6
我有一段代码,如果我在外部 div 上应用 text-decoration: line-through;,则所有内部 div 元素也必须被删除线。 这通常能够完美运行;但是,如果我将子元素设置为 'display:inline-block',现在应用于父 div 的删除线不会影响子元素的删除线。 我必须将子元素设置为 display:inline-block,并且需要在添加 text-decoration: line-through;父 div 时将子元素划掉。

div{padding:10px;}
#outer{background:yellow;text-decoration: line-through;}
#inner{background:pink;display:inline-block;}
<div id=outer> 
  <div id=inner>
    This is the text 
  </div> 
</div>

这是一个办公项目,非常感谢您的帮助!


1
你忘记了在 id 周围加上 " 引号。就像这样 id="outer" - Amit Soni
2
不会有影响的兄弟。那不是问题。结果会一样... - Deadpool
1
@AmitSoni 在HTML5中不需要。 - CodingIntrigue
2个回答

9
使用 text-decoration:inherit

div{padding:10px;}
#outer{background:yellow;text-decoration: line-through;}
#inner{background:pink;display:inline-block; text-decoration:inherit}
<div id=outer> 
  <div id=inner>
    This is the text 
  </div> 
</div>

通常,text-decoration不是继承属性,所以内部的div具有隐式的text-decoration:none,即默认值。通过使用inherit,您告诉元素它应该具有与其父元素相同的文本装饰。


1
“inherit”指示元素从其父元素继承CSS样式。 - Ben
1
我编辑了问题以解释为什么它有效。然而,一个更好的问题是,如果它是“块状”或“内联”,为什么该行可以通过内部div看到。我不确定我能回答这个问题。 - Mr Lister
1
我很惊讶text-decoration不会被继承;我原以为所有的样式都是默认继承的。特别是因为这个"Text decorations draw across descendant elements." - Aaron Digulla
2
请注意,文本装饰不会传递给浮动和绝对定位的后代元素,也不会传递给原子内联级后代元素(如内联块和内联表格)的内容。解释在这里:W3C。这意味着除非明确指定,否则子元素不会继承该属性。 - Bladepianist
3
@AaronDigulla 许多样式是继承的,但并非所有样式都是如此。这里有一个列表。 - Mr Lister

6

text-decoration 的默认值是 none,所以如果想要不同的值,需要指定它。使用 inherit 可以使用父元素的值:

#outer > div { text-decoration: inherit; }

或者调整 #inner 的 CSS 样式,添加 text-decoration: inherit;
#inner { background: pink; display: inline-block; text-decoration: inherit; }

例子

div{padding:10px;}
#outer{background:yellow;text-decoration: line-through;}
#inner{background:pink;display:inline-block; text-decoration: inherit; }
<div id=outer> 
  <div id=inner>
    This is the text 
  </div> 
</div>


1
为什么在这里使用“inherit”会有所不同?难道那不应该是默认值吗? - Aaron Digulla
2
"text-decoration" 的默认值为 "none",如果您想要不同的值,则需要指定一个值。 - Ben

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接