我已经为HTML / CSS网站侧边栏编写了代码,并且我想确保当用户将鼠标悬停在侧边栏中的元素上时,其背景会突出显示。
它仅显示我的普通列表,并且悬停功能不起作用。有什么问题吗?
body {
margin: 0;
}
.sidebar {
float: right;
background-color: #F4ECFC;
/* Sidebar Background */
width: 200px;
/* Width of side bar */
height: 900px;
padding-top: 0px;
/* Padding above the header */
font-family: helvetica;
/* Font for the sidebar */
}
.sidebar a {
text-decoration: none;
/* Removes the underline from links. */
color: #0B0036;
/* Text color of the menu items */
}
.sidebar ul {
line-height: 40px;
overflow: hidden;
margin-left: 0;
padding-left: 0;
}
.sidebar ul li .listItemA {
/* list-style-type: none; */
background-color: #F4ECFC;
/* Background colour of the menu items. */
}
.sidebar ul li .listItemA a:hover {
background-color: purple;
}
.listItemA {
text-align: center;
}
<div class="sidebar">
<ul>
<li class="listItemA"><a href="#">Class1</a></li>
<li class="listItemA"><a href="#">Class2</a></li>
<li class="listItemA"><a href="#">Class3</a></li>
<li class="listItemA"><a href="#">Class4</a></li>
<li class="listItemA"><a href="#">Class5</a></li>
</ul>
</div>
答案 0 :(得分:0)
您首先要做的一件事就是给您的链接display: block;
占用可用宽度的100%。
然后简化链接和相对悬停的样式,如下所示:
.sidebar ul .listItemA {
/* list-style-type: none; */
background-color: #F4ECFC;
/* Background colour of the menu items. */
}
.sidebar ul .listItemA:hover a {
background-color: purple;
}
正如在对您的问题的评论中所指出的,您在li
和.listItemA
之间留有一个空格,我刚刚删除了li
以实现正确的选择器,但您也可以更改该选择器li.listItemA
的选择器的一部分。
真正重要的更改是在悬停列表项时设置链接的样式:
.sidebar ul .listItemA:hover a { ... }
这告诉浏览器在列表项悬停时更改链接的背景。
body {
margin: 0;
}
.sidebar {
float: right;
background-color: #F4ECFC;
/* Sidebar Background */
width: 200px;
/* Width of side bar */
height: 900px;
padding-top: 0px;
/* Padding above the header */
font-family: helvetica;
/* Font for the sidebar */
}
.sidebar a {
display: block;
text-decoration: none;
/* Removes the underline from links. */
color: #0B0036;
/* Text color of the menu items */
}
.sidebar ul {
line-height: 40px;
overflow: hidden;
margin-left: 0;
padding-left: 0;
}
.sidebar ul .listItemA {
/* list-style-type: none; */
background-color: #F4ECFC;
/* Background colour of the menu items. */
}
.sidebar ul .listItemA:hover a {
background-color: purple;
}
.listItemA {
text-align: center;
}
<div class="sidebar">
<ul>
<li class="listItemA"><a href="#">Class1</a></li>
<li class="listItemA"><a href="#">Class2</a></li>
<li class="listItemA"><a href="#">Class3</a></li>
<li class="listItemA"><a href="#">Class4</a></li>
<li class="listItemA"><a href="#">Class5</a></li>
</ul>
</div>