下拉子菜单自动宽度不起作用

时间:2016-12-28 18:30:54

标签: html css drop-down-menu

我有一个简单的下拉菜单,如果子菜单项大或小,我希望子菜单的宽度占用所需的空间。

现在,它包裹在第二行..见

https://jsfiddle.net/nyb44xbd/1/

我试过宽度:自动;不起作用。

CSS:

.dropdown {
     position: relative;
    display: inline-block;
    margin:0 12px;
}

.dropdown-content {
    display: none;
    position: absolute;
    background:white;
    width:auto;

    padding: 12px 16px;
    z-index: 1;

}

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

.subm{margin:12px 0;} 

我的HTML:

<div class="dropdown">
    <span>PRODUCT INFO</span>
    <div class="dropdown-content">
        <div class="subm"><a class="menulink" href="#ingredients">INGREDIENTS</a></div>
        <div class="subm"><a class="menulink subm" href="#ingredients">CUSTOMER REVIEWS</a></div>
        <div class="subm"><a class="menulink subm" href="#ingredients">NUTRITIONAL FACTS</a></div>
        <div class="subm"><a class="menulink subm" href="#ingredients">ORDER NOW</a></div>
    </div>
</div>

由于

3 个答案:

答案 0 :(得分:0)

您可以将position:relative放置在身体上,这样宽度可以变化。

https://jsfiddle.net/0huz4dam/

答案 1 :(得分:0)

尝试将position: relative用于.dropdown。请参阅下面的代码:

&#13;
&#13;
.dropdown {
  position: relative;
  display: inline-block;
  margin: 0 12px;
}

.dropdown-content {
  display: none;
  position: relative;
  background: white;
  width: auto;
  padding: 12px 16px;
  z-index: 1;
}

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

.subm {
  margin: 12px 0;
}
&#13;
<div class="dropdown">
  <span>PRODUCT INFO</span>
  <div class="dropdown-content">
    <div class="subm"><a class="menulink" href="#ingredients">INGREDIENTS</a></div>
    <div class="subm"><a class="menulink subm" href="#ingredients">CUSTOMER REVIEWS</a></div>
    <div class="subm"><a class="menulink subm" href="#ingredients">NUTRITIONAL FACTS</a></div>
    <div class="subm"><a class="menulink subm" href="#ingredients">ORDER NOW</a></div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

只需从position:absolute样式中移除.dropdown-content

即可

.dropdown {
  position: relative;
  display: inline-block;
  margin: 0 12px;
}
.dropdown-content {
  display: none;
  background: white;
  padding: 12px 16px;
  z-index: 1;
}
.dropdown:hover .dropdown-content {
  display: block;
}
.subm {
  margin: 12px 0;
}
<div class="dropdown">
  <span>PRODUCT INFO</span>
  <div class="dropdown-content">
    <div class="subm"><a class="menulink" href="#ingredients">INGREDIENTS</a>
    </div>
    <div class="subm"><a class="menulink subm" href="#ingredients">CUSTOMER REVIEWS</a>
    </div>
    <div class="subm"><a class="menulink subm" href="#ingredients">NUTRITIONAL FACTS</a>
    </div>
    <div class="subm"><a class="menulink subm" href="#ingredients">ORDER NOW</a>
    </div>
  </div>
</div>