首页 > 解决方案 > 如何使用 CSS 更改侧边栏中所选选项的颜色?

问题描述

我无法弄清楚如何更改边栏中所选选项的颜色。例如,我有 4 个选项,我单击第一个选项,我希望侧边栏中的第一个选项始终具有白色背景色。我现在只有一个悬停选项,它会改变背景颜色。我可以只使用 CSS HTML 吗?根据我的研究,我在 JavaScript 和 PHP 中看到了一些,但想知道我是否可以只使用 CSS HTML 来做到这一点。以下是我当前的代码:

.flexContainer {
    display: flex;
}

.flexContainer > div {
    margin: 10px;
    padding: 20px;
    font-size: 20px;
    text-align: center;
}

.sidebarContainer {
    flex-shrink: 1;
}

.sidebar {
    width: 200px;
    background-color: #dd1d5e;
    overflow: auto;
    border-radius: 30px;
}

.sidebar a {
    display: block;
    color: white;
    padding: 16px;
    text-decoration: none;
}

.sidebar a:hover:not(.active) {
    background-color: #ffffff;
    color: #dd1d5e;
}
<div class="flexContainer">
            <div class="sidebarContainer">
                <div class="sidebar">
                    <a href="category.php">Holiday</a>
                    <a href="category.php">Vegetarian</a>
                    <a href="category.php">Dessert</a>
                    <a href="category.php">Cultural Cuisine</a>
                </div>
            </div>
</div>

标签: htmlcss

解决方案


如果你想让它在没有 PHP 的独立 HTML 中工作。首先,您应该有 4 个 HTML 文件,每个文件应该有不同的名称,例如 cat-holiday.htm、cat-vegetarian.htm、cat-dessert.htm 和 cat-culture.htm。

之后,每个 HTML 文件都有一个 ONE,<a>其中包含一个特殊的 CSS 类名,例如:.selected. cat-holiday.htm 样本

            <div class="sidebar">
                <a href="category.php" class="selected">Holiday</a>
                <a href="category.php">Vegetarian</a>
                <a href="category.php">Dessert</a>
                <a href="category.php">Cultural Cuisine</a>
            </div>

最后,您可以在 CSS 文件中添加相应的代码。

.sidebar a.selected {
    background-color: #ff0000;
    color: #00ffff;
}

推荐阅读