Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS specificity problem

I'm working on creating a javascript game for my own education. The game requires several pages, which I'm implementing through hidden divs that get hidden/unhidden when you want to view them (offtopic: Any advice about whether or not that's a good idea is welcome).

I have a CSS rule that hides all of my divs with display: none; and then a class that unhides a specific div with display:block;. However, instead of the class unhiding, it seems that my css selector for selecting all the divs is overriding the class, resulting in the rule not applying. I know I can just use the !important property to fix this, but I want to understand why what I've written doesn't work. I thought that a class would be a specific enough selector, and the rule even comes after the hiding rules.

Here's my source:

<!DOCTYPE HTML>
<html>
<head>
    <link rel="stylesheet" href="style.css" type="text/css" media="screen" charset="utf-8">
</head>
<body>
    <div id="game">
        <div id="content">
            <div id="viewport">
                <div id="home_page" class="current_page">Home</div>
                <div  id="work_page">Work</div>
            </div>
        </div>
    </div>
</body>
</html>

and css:

#content
{
    background: #eef;
    padding: 5px;
}

#viewport div
{
    display:none;
}

.current_page
{
    display:block;
    //display:block !important; //One solution, but not preferred
}
like image 300
Conrad.Dean Avatar asked May 13 '26 22:05

Conrad.Dean


2 Answers

#viewport div is an ID selector and a type selector. That's more specific than .current_page, a class selector by itself, because of the ID alone.

Instead of applying display: block !important;, you can and should modify your last selector, giving it the ID so it becomes #viewport .current_page. This makes the IDs equally specific, with the class selector being more specific than the type selector.

like image 75
BoltClock Avatar answered May 15 '26 17:05

BoltClock


Does this work?

#viewport div.current_page
{
   display:block;
   /* display:block !important; //One solution, but not preferred */
}
like image 23
BNL Avatar answered May 15 '26 16:05

BNL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!