Home > Enterprise >  Add CSS class to all heading HTML elements?
Add CSS class to all heading HTML elements?

Time:09-21

I'm currently working on a website for some school assignments. I am using Wordpress with the Divi theme.

Online I found some CSS code, which lets me add a colored line under my text. I've been using this on all my headings.

  • Here's an example of my headings: H2 with display: table

    CodePudding user response:

    I'm assuming you didn't understand my previous comment so this is an explanation. The tag header is not just the text its a full box of width:auto as you can see in the image above (second background). In the code you sent you're giving the underline effect "box-shadow" to the header h2 which will as explained gives it to the whole box. The text you have written inside h2 are inside a span tag which will only cover the text not the whole box, so giving the effect to only the span tag will fix your problem, and about other h2 tags not getting underline, is because you switched the effect to span, so you have to also put the other h2 inside a span. And since you want to add h3 with different properties, the optimal way to do it is add span to all headers add class name or id for h2 different than h3 and use that class name or id to set the CSS. for example:

    HTML:
    <h2><span id="TextInsideH2" class="pa-color-highlight">Background</span></h2>
    <h3><span id="TextInsideH3" class="pa-color-highlight">Background</span></h3>
    
    CSS:
    #TextInsideH2{css properties here}
    #TextInsideH3{different css properties here}
    

    CodePudding user response:

    As previously said, skip the span part and apply it directly to the h2. Header elements are block level by default which is why you see the background/fat underline stretch across the whole parent element. You'll have to add display:inline-block;, display:inline-flex; or display:table; for example to have the underline only covering the width of the h2 text though:

    h2 {
      display:inline-block;
      text-decoration: none;
      box-shadow: inset 0 -.4em 0 rgba(48, 227, 255, 1);
      color: inherit;
    }
    

    Not knowing how the rest of how your markup looks, this should work as a solution for you. If you want to dig deeper, you can get this effect with pseudo elements. That will give you even better control over how you want that line/background to look. Here's an example:

    h2 {
      position:relative;
      display:inline-block;
    }
    
    h2::before {
      content:'';
      position:absolute;
      bottom:-2px;
      left:-5px;
      right:-5px;
      height:14px;
      background:linear-gradient(to bottom, rgb(48, 227, 255), rgba(32, 160, 255));
      z-index:-1;
    }
    <h2>Background</h2>
    <p>A paragraph</p>

    Here's some more info what pseudo classes can do: CSS-tricks

  • Related