【问题标题】:Style a div's innertext but not if it's a p element with CSS为 div 的内部文本设置样式,但如果它是带有 CSS 的 p 元素则不设置样式
【发布时间】:2023-01-12 22:28:22
【问题描述】:

给定以下 HTML:

<div class="container">
  A. should be bold
</div>

<div class="container">
  <h3>B. should be bold</h3>
  <p>C. should not be bold</p>
</div>

<div class="container">
  <p>D. should not be bold</p>
</div>

以下样式设置了 innerText,但随后也设置了所有后代的样式:

.container {
  font-weight: bold;
}

以下几乎可以解决问题,除了 'A.应该是粗体'不是粗体:

.container {
  :first-child:not(p) {
    font-weight: bold;
  }
}

我知道这可以通过类“.bold”轻松完成,但它需要是动态的。理想情况下不要覆盖任何样式,因为在应用程序中,元素也会获得一些额外的样式,我不想覆盖这些样式。

【问题讨论】:

    标签: css


    【解决方案1】:

    尝试这个 :

    .container {
      font-weight: bold;
    }
    .container p{
      font-weight: normal;
    }
    

    【讨论】:

      【解决方案2】:

      如果不是,这将使内容加粗P标签

      .container:first-child:not(p) {
         font-weight: bold;
      }
      <div class="container">
        A. should be bold 
      </div>
      
      <div class="container"> 
        <h3>B. should be bold</h3> <p>C. should not be bold</p> 
      </div> 
      
      <div class="container"> 
        <p>D. should not be bold</p> 
      </div>

      【讨论】:

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