Background Color change on a:hover

2019-08-21 14:25发布

问题:

So I basically want to take a navigation i created with div's and make it so that each line (id) will rollover a different color.

I've tried a ton of different ways of doing it and I'm getting stuck with using the ID correctly I believe.

<div class="navcontainer">
        <div id="1"><a href="#">home</a></div>
        <div id="2"><a href="#">work</a></div>
        <div id="3"><a href="#">resume</a></div>
        <div id="4"><a href="#">about</a></div>
        <div id="5"><a href="#">links</a></div>
</div>

And the CSS

.navcontainer {
font-family: Arial, Helvetica, sans-serif;
font-size:24px;
display:block;
}
.navcontainer div a {
background-color:black;
margin:2px;
padding:2px;
display:inline;
float:left;
clear:both;
color:white;
text-decoration:none
}
.navcontainer #1 a:hover {
color:black;
background-color:red;
}
.navcontainer #2 a:hover {
color:black;
background-color:orange;
}

回答1:

Never start ID & Class with numerical (1,2,3,) digit. Write like this:

#nav1,#nav2...

HTML

<div class="navcontainer">
        <div id="nav1"><a href="#">home</a></div>
        <div id="nav2"><a href="#">work</a></div>
        <div id="nav3"><a href="#">resume</a></div>
        <div id="nav4"><a href="#">about</a></div>
        <div id="nav5"><a href="#">links</a></div>
</div>


回答2:

Change your ID names to be alpha not starting with a number..

IE:

.navcontainer #one a:hover {
color:black;
background-color:red;
}

<div class="navcontainer">
    <div id="one"><a href="#">home</a></div>
    <div id="2"><a href="#">work</a></div>
    <div id="3"><a href="#">resume</a></div>
    <div id="4"><a href="#">about</a></div>
    <div id="5"><a href="#">links</a></div>
</div>