覆盖子元素上的文本修饰

时间:2016-03-21 13:02:45

标签: html css css3

我想覆盖子元素中的父css。 我想为父元素加下划线,但不是子元素。

.parent {
  text-decoration: underline;
  color: red;
}
.child {
  color: green;
  text-decoration: none !important;
}
.sub-child {
  color: green;
  text-decoration: none !important;
}
<div class="parent">Inside parent
  <div class="child">Inside first child
    <div class="sub-child">Inside 1st child of 1st child
    </div>
  </div>
  <div class="child">Inside 2nd child
    <div class="sub-child">Inside 1st child of 2nd child</div>
    <div class="sub-child">Inside 2nd child of 2nd child</div>
  </div>
  <div class="child">
    Inside 3rd child
    <div class="sub-child">Insde 1st child of 3rd child</div>
  </div>
</div>

4 个答案:

答案 0 :(得分:3)

MDN

中所述
  

文本装饰跨越后代元素。这意味着它   无法在后代上禁用文本修饰   在其祖先的一个上指明。

所以,不幸的是,你不能。正如其他人所述,唯一的解决方案是用相应的标签包装相应的文本,例如:一个span

答案 1 :(得分:0)

您可以通过在父元素文本中添加span来完成此操作

<强> HTML

<div class="parent"><span class="parent_text">Inside  parent</span>
            <div class="child">Inside first child
                <div class="sub-child">Inside  1st child of 1st child
            </div>
            </div>
            <div class="child"> Inside 2nd child
                    <div class="sub-child">Inside 1st child of 2nd child</div>
                    <div class="sub-child">Inside 2nd child of 2nd child</div>
                </div>
                <div class="child">
                Inside 3rd child
                    <div class="sub-child">Insde 1st child of 3rd child</div>
                </div>
        </div>

<强> CSS

.parent span.parent_text{
    text-decoration:underline;
}

答案 2 :(得分:0)

当jQuery被标记时,你可以这样做:

&#13;
&#13;
$('.parent').contents().filter(function(i,el){
  return el.nodeType === 3;
}).wrap('<em>')
&#13;
.parent em{
  text-decoration: underline;
  color: red;
}
.child {
  color: green;
  text-decoration: none !important;
}
.sub-child {
  color: green;
  text-decoration: none !important;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">Inside parent
  <div class="child">Inside first child
    <div class="sub-child">Inside 1st child of 1st child
    </div>
  </div>
  <div class="child">Inside 2nd child
    <div class="sub-child">Inside 1st child of 2nd child</div>
    <div class="sub-child">Inside 2nd child of 2nd child</div>
  </div>
  <div class="child">
    Inside 3rd child
    <div class="sub-child">Insde 1st child of 3rd child</div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

正如 xpy 所述,这是不可能的,并且是text-decoration的限制,无法用正常级联或!important覆盖。如果你不愿意添加额外的标记(比如span),你唯一的另一个选择可能是使用边框来伪造这个外观(它将跨越你的整个div,而不仅仅是文本的长度) ),例如,

.parent > .child:first-of-type {
        border-top:1px solid red;
}