Satyam Kumar Satyam Kumar - 3 years ago 171
CSS Question

My Responsive Navigation Bar Doesn't functioning well

I have made a responsive navigation bar for Mobile screen but it's not working well. It gets shrink when its come to the mobile screen but when I clicked on icon nav bar doesn't expand on the mobile screen.
The click icon button doesn't work on when comes on mobile screen.
My code is here. Please help..

<body>

<div class="first" id="myfirst">
<a href="#home">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
<a href="#about">About</a>
<a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="myFunction()">&#9776;</a>
</div>
<script>
function myFunction() {
var x = document.getElementById("myfirst");
if (x.className === "first") {
x.className += " responsive";
} else {
x.className = "first";
}
}

</script>

</body>

body {margin:0;}

.first { overflow: hidden;
background-color: #333;
}

.first a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}

.first a:hover {
background-color: #ddd;
color: black;
}

.first .icon {
display: none;
}

@media screen and (max-width: 600px) {
.first a:not(:first-child) {display: none;}
.first a.icon {
float: right;
display: block;
}
}

@media screen and (max-width: 600px) {
.responsive {
position: relative;
}
.responsive .icon {
position: absolute;
right: 0;
top: 0;
}
.responsive a {
float: none;
display: block;
text-align: left;
}

}

Answer Source

The effect is not as desired because CSS is Cascading and .first a:not(:first-child) selector has more priority then .responsive a one.

So, the quickest way to fix your code is to change last .responsive a selector in this way:

.responsive a:first-child,
.responsive a:not(:first-child) {
  float: none;
  display: block;
  text-align: left;
}

Finally, just a couple of suggestions:

  • is better to use nav HTML5 element instead of div: it strengthen code semantics
  • avoid identical @media screen and (max-width: 600px) { media queries: it weakens readability and maintainability
  • improve class semantics giving more suitable names (eg: rename responsive in open)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download