How to set styles for different headlines (h1, h2, ...) in CSS?

14,487

Solution 1

You're not correclty using css selectors.

To select the h1 on your page which has a class version-one (or respectively version-two), just type this:

HTML:

<h1 class="version-one">red headine</h1>
<h1 class="version-two">blue heading</h1>

CSS:

.version-one {
    /* your styles for the class version-one */
    font-size: 3em;
    color: red;
}

.version-two {
    /* your styles for the class version-two */
    font-size: 3em;
    color: blue;
}

You also could use h1.version-one as the selector to ensure you're only targetting h1-elements with this class and not other elements with this class (e.g. a paragraph).

Solution 2

Use it the other way around, so:

CSS

.version-one h1 {
    color: red;
}
.version-one h2 {
    color: orange;
}

.version-two h1 {
    color: blue;
}
.version-two h2 {
    color: purple;
}

HTML

<div class="version-one">
    <h1>lorem lipsum</h1>
    <h2>lorem lipsum</h2>
</div>

<div class="version-two">
    <h1>lorem lipsum</h1>
    <h2>lorem lipsum</h2>
</div>

This works.

The jsfiddle

Share:
14,487
user2164961
Author by

user2164961

Updated on June 05, 2022

Comments

  • user2164961
    user2164961 almost 2 years

    I would like to have two different styles for the h1, h2, h3 etc.

    I tried using classes for the styles like this:

    .version-one{
    h1{
        ...
    }
    h2{
        ...
    }
    }
    

    And then in the html:

    <h1 class="version-one">Title</h1>
    

    But this did not work. Is there a way to do this?

    Thank you very much :)

  • Marco Geertsma
    Marco Geertsma almost 11 years
    wow a downvote in less then 20 seconds? Im interested why that would be?
  • Marco Geertsma
    Marco Geertsma almost 11 years
    @kleinfreund how about now?
  • Admin
    Admin almost 11 years
    The jsFiddle works, because you add the generated css there, the syntax you wrote, is something like LESS and need compile before browser can understand it. Btw, i'm not the cause of downvote ;). +1 for editing it.