问题
Recently I answered a question and the OP wanted text-decoration: underline;
for the entire text wrapped inside the a
element, but not the one wrapped inside span
, so it was something like this
<a href="#"><span>Not Underline</span>Should Be Underlined</a>
So simply giving
span {
text-decoration: none;
}
doesn't remove the underline for the text wrapped inside a span
element
But this does remove the underline
span {
text-decoration: none;
display: inline-block;
}
So I made the span
an inline-block
and it worked, which is how I usually do it. But when it came to explanation I was not able to explain why doing this actually removes the underline where simply using text-decoration: none;
doesn't.
Demo
回答1:
Text decorations are propagated from an element to certain descendants in certain cases. The spec describes all the cases in which this happens and doesn't happen (as well as cases where the behavior is explicitly undefined). Here, the following portion is relevant:
Note that text decorations are not propagated to floating and absolutely positioned descendants, nor to the contents of atomic inline-level descendants such as inline blocks and inline tables.
Note that this propagation is not the same as inheritance and is a separate concept entirely; indeed, text-decoration: none
and text-decoration: inherit
do not affect propagation in the way you'd expect them to:
text-decoration: none
simply means "this element has no text decorations of its own", andtext-decoration: inherit
means "this element has the same specifiedtext-decoration
value as its parent."
In both situations, parent text decorations will still be propagated to the element where applicable. You can force an inline-block to have the same text decoration as its parent using inherit
, but not any other decorations that the parent gains through propagation from its own ancestors.
This also means that simply having display: inline-block
is enough to prevent the text decorations from being propagated. You do not need to specify text-decoration: none
again — it's already the initial value.
来源:https://stackoverflow.com/questions/13857853/why-does-display-inline-block-remove-an-underline-from-a-child-element