Petr Bečka Petr Bečka - 4 months ago 16
CSS Question

CSS: make drop-down menu as wide as top bar

I've made a top bar that contains drop-down MENU button on the right side. But this drop-down content has exactly the same size (width) as my MENU button. Finally - my goal is to make this drop-down content as wide as the top bar is.

My HTML code looks like this:

<div id="top-bar">
<div class="dropdown">
<button class="dropbtn">MENU</button>
<div class="dropdown-content">
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
</div>
</div>
</div>


And more important part - CSS:

#top-bar{
left: 0;
top: 0;
float: left;
width:100%;
height:40px;
background-color: black;
}
.dropbtn {
background-color: blue;
color: white;
height: 40px;
font-size: 12px;
border: none;
cursor: pointer;
}
.dropdown {
float: right;
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
float: left;
position: absolute;
background-color: #f9f9f9;
width: 100%;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}
.dropdown-content a {
color: black;
padding: 10px 14px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {background-color: #f1f1f1}
.dropdown:hover .dropdown-content {
display: block;
width: 100%;
float: left;
left: 0;
}
.dropdown:hover .dropbtn {
background-color: blue;
}


If you want to see how does it look like HERE is jsFiddle link.

Don't you have any idea how to solve my problem?

Answer

Just move position: relative from .dropdown to #top-bar.

By doing this, .dropdown-content will calculate width according to the nearest element with position: relative i.e #top-bar.

#top-bar{
  position: relative;
  height:40px;
  float: left;
  width: 100%;
  background-color: black;
}

.dropbtn {
  background-color: blue;
  color: white;
  height: 40px;
  font-size: 12px;
  border: none;
  cursor: pointer;
}

.dropdown {
  float: right;
}

.dropdown-content {
  display: none;
  left: 0;
  top: 100%;
  position: absolute;
  background-color: #f9f9f9;
  width: 100%;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
  color: black;
  padding: 10px 14px;
  text-decoration: none;
  display: block;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
  display: block;
}

.dropdown:hover .dropbtn {
  background-color: blue;
}
<div id="top-bar">
  <div class="dropdown">
    <button class="dropbtn">MENU</button>
    <div class="dropdown-content">
      <a href="#">Link</a>
      <a href="#">Link</a>
      <a href="#">Link</a>
    </div>
  </div>
</div>