导航子菜单链接列出容器的整个宽度,而不是它们嵌套的菜单项的宽度

时间:2015-04-02 17:42:27

标签: html css nav submenu

我正在当前简单的Nav菜单栏上创建Sub Menus。当我将鼠标悬停在导航链接上进行“处理”时,子菜单项会很好地下拉到上面链接的中心,但背景颜色会在整个容器中传播(与完整导航栏的宽度相同)。我想要的是子菜单下拉到与上面“治疗”链接相同的宽度。 我在下面添加了片段,供人们查看我出错的地方。

@charset"UTF-8";

nav {
  font-size: 20px;
  text-transform: uppercase;
  background-color: #1C75BC;
  color: white;
}
nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
nav ul:after {
  content: "";
  clear: both;
  display: block;
}
nav li {
  float: left;
  width: 20%;
}
nav a:link,
nav a:visited {
  display: block;
  color: white;
  background-color: #1C75BC;
  text-align: center;
  padding: 8px;
  text-decoration: none;
  transition: all 0.3s ease-in;
  -webkit-transition: all 0.3s ease-in;
  /* Safari */
  -moz-transition: all 0.3s ease-in;
  /* Firefox */
  -o-transition: all 0.3s ease-in;
  /* Opera */
}
nav a:hover {
  background-color: #4dacff;
}
nav ul ul {
  display: none;
  font-size: 10px;
}
nav ul li:hover > ul {
  display: block;
}
nav ul ul li {
  border-radius: 0px;
  padding: 0;
  position: absolute;
}
nav ul ul li {
  float: none;
  position: relative;
  width: auto;
}
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" type="text/css" href="testcss.css">
</head>

<body>
  <nav>
    <ul>
      <li><a href="http://www.leftyslaser.co.uk">Home</a>
      </li>
      <li><a href="http://www.leftyslaser.co.uk/faq.html">FAQ</a>
      </li>
      <li><a href="http://www.leftyslaser.co.uk/portfolio.html">Portfolio</a>
      </li>
      <li><a href="#">Treatments</a>
        <ul>
          <li><a href="#">Laser Tattoo Removal</a>
          </li>
          <li><a href="#">Carbon Facial Skin Rejuvenation</a>
          </li>
        </ul>
      </li>
      <li><a href="http://www.leftyslaser.co.uk/about.html">About Us</a>
      </li>
    </ul>
  </nav>
</body>

2 个答案:

答案 0 :(得分:0)

<强> Demo

使用inline-block代替block。使用display: block可以在整个浏览器中显示元素。

nav ul li:hover > ul {
  display: inline-block;
}

答案 1 :(得分:0)

从导航声明中删除background-color: #1C75BC;