Conflicting CSS Stylings

RichD

New Member
Huy guys,

Im new here (as the post counter suggests) and I have just started getting seriously into web design. I have hacked around a bit with some WYSIWIG editors and done a bit of basic HTML but I am currently working through the W3Schools Html and CSS tutorials... Anyway

One thing that I am not clear on is that with CSS It is possible to add conflicting styles to elements with classes. ie I divide my sites up into three sections using dev tags so that I have a menu at the top a body and a footer and give each section its own class. If I was to use the following code (please excuse any syntax errors as I am free typing from work)

Code:
p {color:black}

.body {text-color:blue}

p.body {text-color:red}

all p text in the page should be black, but all text in the body class (referenced in the dev tags) should be blue but all p text with the body class should be red.

My question is how does the browser decide which style to apply? Is this considered "bad coding"?

Thank you.
 
Last edited:

Phreaddee

Super Moderator
Staff member
Inline takes preference, followed by style in head followed by ext stylesheet, from there preference goes to the last style. For instance you could write, although it would be bad practice, the following
Code:
p {color:black;}
p {color:blue;}
p {color:red;}
In that example the first two options would be ignored.
Yet if within your html page you had
HTML:
<p style="color:black;">... </p>
Your paragraph would be black.
 

Phreaddee

Super Moderator
Staff member
On a side note, do you mean the body tag or a class called .body? As that in itself would be slightly confusing...personally I would never call a class "body"
 

PixelPusher

Super Moderator
Staff member
On a side note, do you mean the body tag or a class called .body? As that in itself would be slightly confusing...personally I would never call a class "body"

Agreed. For semantic reasons I never use elements names in class or id names. When creating class/id names you want to think of the meaning/role that element posses. For example "div.sidebar". This could be floating left, have green background, serif font, etc. The style of it can change, but the meaning remains the same--its a sidebar.
 
Last edited:

RichD

New Member
I was taking about a class called body. It was just an example but I will try to avoid using it.

Code:
td {color:black}
td.maintext {color:green}

In the above example td would be black unless it has the assigned class maintext

Code:
td.maintext {color:green}
td {color:black}

Am I right in assuming that in the example above it will read the last td thus rendering the first line and the class irrelevant?
 

Phreaddee

Super Moderator
Staff member
No because specifity would trump a general rule, all tds would be black except those with the class rule applied to it, which would be green.
 
Top