SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    May 2005
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Basic CSS Inheritance Question

    I am a complete newbie to CSS and am learning it from the Apress book called Beginning CSS Web Development: From Novice to Professional. I have a question regarding inheritance. My stylesheet is:

    Code CSS:
    #container{
       padding: 20px;
    	border: 1px solid #000;
    	background: #CCC;
    }
     
    .box{
    	margin: 10px;
    	padding: 20px;
    	border: 1px solid #000;
    }
     
    .box p{
    	color: red;
    }
     
    #container p{
    	color: blue;
    }

    and my HTML file is

    Code HTML4Strict:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    	<title>Learning Page</title>
    	<link rel="stylesheet" type="text/css" href="external.css"></link>
    </head>
     
    <body>
    <div id="container">
    <p>This is our content area.</p>
    <div class="box"><p>This is another test.</p></div>
    <div class="box"><p>This is a test.</p></div>
    </div>
    </body>
    </html>

    From what I understand, and from what it shows in the book the paragraph contained in the box class (This is another test and This is a test.) should show in red, but it shows up in blue. If I am explicitely defining that paragraphs if the class is box should show up in red, why is it inheriting the color from the container id? What am I doing wrong?

  2. #2
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,158
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This isn't about inheritance, but about the cascade. You have two conflicting declarations for the colour of those paragraphs; one says red, the other says blue.

    The rules of CSS are very clear about which one will eventually be applied. In this case, it boils down to specificity. The selector #container p is more specific (by an order of magnitude) than the selector .box p, and the rule with most specific selector wins. Therefore the text will be blue.

    If you want the red rule to be applied you must make the selector more specific:
    Code CSS:
    #container .box p {color:red}
    Birnam wood is come to Dunsinane

  3. #3
    The CSS Clinic is open silver trophybronze trophy
    Paul O'B's Avatar
    Join Date
    Jan 2003
    Location
    Hampshire UK
    Posts
    40,556
    Mentioned
    183 Post(s)
    Tagged
    6 Thread(s)
    And here's a reference about this that Tommy and I prepared earlier


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •