使用 :has() 伪类在“select”元素中设置样式选项

问题描述 投票:0回答:1

我正在尝试根据 select 元素中所做的选择来设置我的框背景颜色的样式。 挑战是在这里使用 :has() 伪类。 我已经检查过这行代码好几次了,它与选项中选择的内容不符...... 我在这里做错了什么?

Here is an image of what I'm working on

HTML 代码片段

<!DOCTYPE html>
<html lang="en">

<head>
    <link rel="stylesheet" href="testing.css">
</head>

<body>
    <div class="selections">
        <select name="" id="" class="options">
            <option value="green">Green colour</option>
            <option value="red">Red colour</option>
            <option value="blue">Blue colour</option>
            <option value="yellow">Yellow colour</option>
        </select>
    </div>

    <div class="parentBox">
        <div class="box">box</div>
    </div>
</body>

</html>

CSS 代码片段

.selections {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 30vh;
}

.options {
    width: 30%;
    height: 30%;
}

.parentBox {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 40vh;
}

.box {
    box-shadow: 8px 8px 32px;
    width: 50%;
    height: 50%;
}

.selections:has(select > option[value="green"])+.parentBox>.box{
    background-color: limegreen;
    box-shadow: -8px -8px 16px darkgreen;
}

.selections:has(select > option[value="red"])+.parentBox>.box{
    background-color: firebrick;
    box-shadow: -8px -8px 16px red;
}

代码笔: https://codepen.io/Rabbit0929/pen/ZEoKYQE

html css css-selectors
1个回答
2
投票

您需要添加

:checked
伪类,以便样式仅应用于所选选项:

https://codepen.io/jimmys20/pen/oNdWxrr

.selections {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 30vh;
}

.options {
    width: 30%;
    height: 30%;
}

.parentBox {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 40vh;
}

.box {
    box-shadow: 8px 8px 32px;
    width: 50%;
    height: 50%;
}

.selections:has(select > option[value="green"]:checked)+.parentBox>.box{
    background-color: limegreen;
    box-shadow: -8px -8px 16px darkgreen;
}

:root {
  --bg-color: transparent;
  --shadow-color: transparent;
}

.parentBox > .box {
  background-color: var;
    box-shadow: -8px -8px 16px red;
}

.selections:has(select > option[value="red"]:checked)+.parentBox>.box{
    background-color: firebrick;
    box-shadow: -8px -8px 16px red;
}
<body>
    <div class="selections">
        <select name="" id="" class="options">
            <option value="green">Green colour</option>
            <option value="red">Red colour</option>
            <option value="blue">Blue colour</option>
            <option value="yellow">Yellow colour</option>
        </select>
    </div>

    <div class="parentBox">
        <div class="box">box</div>
    </div>
</body>

© www.soinside.com 2019 - 2024. All rights reserved.