简体   繁体   中英

pseudo class hover in CSS

Been trying to learn about CSS and the use of hover psuedo classes over elements. Whenever I select a tab in the navigation bar, the background colour changes colour ( which is what I want). However, when I move off the anchor text the text changes back to white.

Ideally what I'm wanting is for the navigation tab to turn the background colour white, and the text black together simultaneously when the mouse hovers over. Here's the code:

<head>
    <link rel="stylesheet" href="css.css" />
</head>

<body>
    <div id="container">
        <div id="title">
                <h1>Record Store</h1>

        </div>
        <div id="navigation">
            <ul class="navbar">
                <li><a href="#">Home</a>
                </li>
                <li><a href="#">Vinyl Stock</a>
                </li>
                <li><a href="#">Online Offers</a>
                </li>
                <li><a href="#">Collectors News</a>
                </li>
                <li><a href="#">Contact</a>
                </li>
            </ul>
        </div>
    </div>
</body>

and CSS code:

* {
    border: 0;
    padding: 0;
    margin:0;
}
#container {
    margin: auto;
    width: 800px;
    border: 1px solid black;
    min-height: 600px;
    z-index: -9;
}
#title {
    margin:auto;
    /*border: 1px solid black;*/
    height: 30%;
}
#navigation {
    border-top: 1px solid black;
    border-bottom: 1px solid black;
    height: auto;
    overflow: auto;
}
.navbar {
}
.navbar ul {
}
.navbar li {
    font: bold 12px/1.2em Arial, Verdana, Helvetica;
    height: auto;
    list-style: none;
    text-align: center;
    width: 20%;
    float:left;
    background-color: blue;
    padding: 1% 0px;
}
.navbar a {
    border-right: 1px solid #1F5065;
    color: white;
    display: block;
    text-decoration: none;
}
.navbar a:hover {
    color: black;
}
.navbar li:hover {
    background-color: white;
}

Can someone have a look and point out where I'm going wrong?

You just have to be more conscientious about defining your selectors. You're doing one thing when somebody hover over an li and something else when they hover over the a . What you want is to change both elements when hovering over a common element.

To solve the problem, remove:

.navbar a:hover {
    color: black;
}

And replace it with:

.navbar li:hover a {
    color: black;
}

jsFiddle

The first selector says "Get all a:hover 's that are children in .navbar ," The second selector says "Get all a 's that are children in li:hover 's that are children of .navbar. "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM