【问题标题】:css dropdown not workingCSS下拉菜单不起作用
【发布时间】:2016-06-09 22:59:20
【问题描述】:

练习锚标签和下拉菜单。在以下代码中,下拉菜单不起作用。不知道为什么。包含文本“这是下拉菜单”的 div 应该恰好出现在包含文本“这是文本。它在中心”的 div 下方,只要后者悬停在上面。两个 div 的宽度相同。

html,body {
	margin: 0px;
	height: 100%;
	/* [disabled]width: 100%; */
	left: 0px;
	top: 0px;
	background-color: rgba(255,255,255,1);
}

.wrapper {
	text-align: center;
	margin-top: 0;
	margin-left: auto;
	height: 100%;
	max-width: 960px;
	background-color: rgba(0,0,0,1);
	margin-right: auto;
	position: relative;
}

.link1 {
	height: auto;
	width: 50%;
	color: rgba(255,255,255,1);
	margin-right: auto;
	margin-left: auto;
	background-color: rgba(204,204,204,1);
}

.link1 a {
	text-decoration: none;
	display: block;
}

.link1 a:hover {
	text-decoration: underline;
	background-color: rgba(255,0,0,1);	
}

.link1 a:hover .dropdown {
	display: block;
}


.dropdown

{
	height: 25%;
	width: 50%;
	background-color: rgba(204,204,204,1);
	margin-right: auto;
	margin-left: auto;
	text-align: center;
	display: none;
}
<div class="wrapper">

<div class="link1">
<a href="http://www.hotmail.com">This is text. Its in center</a>
</div>
<div class="dropdown">This is dropdown menu</div>

</div>

【问题讨论】:

  • 那是因为你的 .dropdown 元素不是链接的兄弟。
  • 能否请您提供代码示例以便我更好地理解?

标签: html css


【解决方案1】:

您的 css 选择器 .link1 a:hover .dropdown 选择类为 dropdown 的元素,该元素必须位于处于悬停状态 (a:hover) 的 a 元素内,该元素位于类为 link1 的元素内。

这与您的 html 标记不匹配。

要使其正常工作,您可以将 html 更改为:

<div class="wrapper">
     <div class="link1">
          <a href="http://www.hotmail.com">
              This is text. Its in center
              <div class="dropdown">This is dropdown menu</div>
          </a>
     </div>
</div>

希望对您有所帮助。

【讨论】:

  • 但在这种情况下,下拉 div 采用 .link1 a:hover 的背景颜色,并且其宽度与上述 div 不匹配
【解决方案2】:

Lexith 部分正确,您需要在容器 div 中添加下拉菜单,然后您可以选择悬停链接的兄弟。

像这样;

CSS -

.link1 a:hover + .dropdown {
    display: block;
}

HTML -

<div class="link1">
  <a href="http://www.hotmail.com">This is text. Its in center</a>
  <div class="dropdown">This is dropdown menu</div>
</div>

CSS 更新 - 这允许下拉菜单在悬停时保持打开状态

.dropdown:hover,
.link1 a:hover + .dropdown {
    display: block;
}

这意味着它没有任何 a 标签样式。 View my code pen

【讨论】:

  • 比我的回答好。我一直忘记用+ 选择兄弟姐妹的可能性。
  • 什么容易做?还记得+ 运算符或提供比我更好的答案吗? :D
  • 感谢您早上的笑声:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-05
  • 2014-04-09
  • 2013-01-08
  • 2013-08-19
  • 1970-01-01
相关资源
最近更新 更多