You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS中~选择器无法选中同一div内子元素的问题求助

CSS ~选择器失效问题的解决方法

问题描述

需要选中同时带有about和one类的div元素,修改其背景色与网格布局,但使用.about ~ .one选择器完全无效,相关代码如下:

HTML代码片段

<div class="about-wrapper">
    <div class="about one">
        <div class="title">
            About Title
        </div>
        <div class="desc">
            A basic description
        </div>
    </div>
</div>

CSS代码片段

.about-wrapper {
    display: grid;  
    grid-template-areas: 
        "About  Empty"
        "Join   Empty";
    grid-template-columns: 1fr 1fr;
    grid-template-rows: 1fr 1fr;
    margin: 12vh;
}

.about {
    background-color: #2b2b2b64;
    border-radius: 2rem;
    padding: 2rem;
    margin: 2vw;
}

.about ~ .one { /* 无法生效的选择器 */
    background-color: #0068bf;
    grid-column-start: 1fr;
    grid-column-end: 3fr;
}

.about .title {
    font-family: 'Rubik 80s Fade', cursive;
    font-size: 2.75vw;
    color: #ffffff;
}

.about .desc {
    font-family: 'Roboto', sans-serif;
    font-weight: 600;
    font-size: 2vw;
    letter-spacing: -0.1vw;
    color: #ffffffe8;
}

问题原因

  1. ~选择器作用误解:~是兄弟选择器,仅匹配同一父元素下、位于.about之后的同级.one元素。而你的场景中about和one是同一个元素的两个类,该选择器完全不匹配目标元素。
  2. 网格属性语法错误:grid-column-start和grid-column-end不能使用fr作为值,这两个属性接受列序号、span关键字或命名区域,fr是定义列宽的单位,不适用于此处。

修正方案

1. 正确使用多类选择器

要选中同时拥有about和one类的元素,需使用多类选择器,将两个类名直接连写(无空格):

.about.one {
    background-color: #0068bf;
    grid-column: 1 / 3; /* 占用第1到第3列,即两列宽度 */
}

2. 修正网格布局属性

将错误的grid-column-start: 1fr和grid-column-end: 3fr替换为以下正确写法之一:

  • 列序号写法:grid-column-start: 1; grid-column-end: 3
  • 简写形式:grid-column: 1 / 3
  • span关键字写法:grid-column: span 2(表示跨越2列)

完整修正后的CSS相关部分

.about {
    background-color: #2b2b2b64;
    border-radius: 2rem;
    padding: 2rem;
    margin: 2vw;
}

.about.one { /* 修正后的选择器 */
    background-color: #0068bf;
    grid-column: 1 / 3; /* 修正网格列属性 */
}

内容的提问来源于stack exchange,提问作者FuryRex09

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 20:30:42