I have the following code:
#main,
#main ul,
#main li,
#main a {
margin: 0;
padding: 0;
border: 0;
list-style: none;
font-weight: normal;
text-decoration: none;
line-height: 1;
font-family: 'Open Sans', sans-serif;
font-size: 14px;
position: relative;
}
#main{
width: 250;
border-right: 1px solid #ececec;
}
#main a {
line-height: 1.3;
}
#main > ul > li {
background: #f7f7f7;
background: -moz-linear-gradient(#f7f7f7 0%, #ececec 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #f7f7f7), color-stop(100%, #ececec));
background: -webkit-linear-gradient(#f7f7f7 0%, #ececec 100%);
background: linear-gradient(#f7f7f7 0%, #ececec 100%);
}
#main > ul > li a:hover {
background: #2E779A;
background: -moz-linear-gradient(#2E779A 0%, #2E779A 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #2E779A), color-stop(100%, #2E779A));
background: -webkit-linear-gradient(#2E779A 0%, #2E779A 100%);
background: linear-gradient(#2E779A 0%, #2E779A 100%);
color: #ffffff;
}
#main > ul > li > a {
font-size: 14px;
display: block;
color: #2E779A;
border: 1px solid #ececec;
border-top: none;
text-shadow: 0 -1px 1px #ececec;
}
<div id="main">
<ul>
<li><a href="#">Inicio</a></li>
<li><a href="#">Sobre nosotros</a></li>
<li><a href="#">Producto</a></li>
<li><a href="#">Contacto</a></li>
</ul>
</div>
And what I want is that when selecting a field, it changes color to show the user which section it is in. Can I do this with css or do I need to use jQuery?
One option to do it with just HTML and CSS (no JavaScript or jQuery) would be to use
:target
. The pseudo-class:target
represents a single element whoseid
matches the identifier fragment of the page URI (the part after the hash #). So for example, if the URL ishttp://mi.pagina.com/index.php#seccion-2
, the element that will be selected with:target
will be the one withid="seccion-2"
.The advantages of this method are that it is easy to develop and does not require JavaScript; the drawbacks are that it is not supported in older versions of IE (8 and below) and that if you use internal links (to anchors inside the page) it would not work well at all and would require quite a few changes... but if that is not your case , this is a clean and simple solution.
The steps to change the code above would be very simple:
Add a
id
unique to each link within the menu:Make each link point to its own
id
:Define the styles you want to highlight the active menu. For example, if you want it to have a red background and white letters:
Here you can see a demo of how it would be:
I've added a style and a click
.seleccionado
event handler to your example . Then using addClass and removeClass the desired effect is produced.Advantages: you do not need to modify your structure or use fixed ids.-
Disadvantages: you have to use jQuery.