DJC
DJC

Reputation: 1173

Using one class with different HTML elements

I am trying to simplify my CSS and can't get my head around why I can't apply styles to different element types with the same class.

For example, the below will only style all the .forum elements navy, but the other more specific styles are ignored. Is there a way around this?

EDIT http://jsfiddle.net/fWvxs/

HTML

<h1 class="forum">Forum Header</h1>

    <p class="forum">Forum Content</p>

    <small class="forum">Small deets</small>

CSS

.forum {
color: navy;
}

.forum h1 {
    text-decoration: underline;
}

.forum small {
    font-size: 2em;
}

Upvotes: 0

Views: 55

Answers (5)

JohanVdR
JohanVdR

Reputation: 2878

It depends also what you want to achieve. In case you want to have define a forum style. You better add the class for example to the div instead of each element individually. You would otherwise repeatedly adding the class forum to each element.

<div class="forum">
    <h1>Forum Header</h1>
    <p>Forum Content</p>
    <small>Small deets</small>
</div>

.forum {/* PUT HERE THE FORUM DEFAULT STYLES WHICH ARE COMMON LIKE IE. COLOR, FONT-SIZE */}
.forum h1 {/* PUT HERE H1 FORUM STYLES WHICH ARE SPECIFIC -THESE WILL BE OVERRIDDEN IF DECLARED in .forum {} */}
.forum p {/* PUT HERE P FORUM STYLES WHICH ARE SPECIFIC -THESE WILL BE OVERRIDDEN IF DECLARED in .forum {} */}
.forum small {/* PUT HERE SMALL FORUM STYLES WHICH ARE SPECIFIC -THESE WILL BE OVERRIDDEN IF DECLARED in .forum {} */}

On the other hand if you need to apply a forum style to an individual element like a p and not the other elements you add the class to the element directly.

  <div>
    <h1>Forum Header</h1>
    <p class="forum">Forum Content</p>
    <small>Small deets</small>
</div>

p.forum {}

Upvotes: 0

InventorX
InventorX

Reputation: 378

You have problem in Css Style, Correct CSS is:

.forum {
color: navy;
}

h1.forum  {
    text-decoration: underline;
}

small.forum  {
    font-size: 2em;
}

Upvotes: 0

ashishmaurya
ashishmaurya

Reputation: 1196

this should work

.forum {
color: navy;
}

h1.forum  {
    text-decoration: underline;
}

small.forum  {
    font-size: 2em;
}

Upvotes: 1

it should be like this

h1.forum {
  text-decoration: underline;
}

.forum h1 { //this applies to a h1 inside the .forum class element
    text-decoration: underline;
}

Upvotes: 1

King King
King King

Reputation: 63377

Try this:

.forum {
  color: navy;
}

h1.forum {
  text-decoration: underline;
}

small.forum {
  font-size: 2em;
}

Note that you used the wrong selector, .forum h1 means selecting the h1 which is one descendant of the .forum while h1.forum means selecting the h1 element having class forum.

Upvotes: 4

Related Questions