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

为何我的搜索栏容器CSS :focus伪类不生效?技术求助

搜索栏容器:focus伪类不生效的修复方案

问题根源

form标签默认不属于可聚焦元素,点击搜索框时,焦点只会落在内部的<input>上,而非form容器本身,所以直接给.search-bar设置:focus伪类无法触发样式变化。

解决方法

使用CSS的:focus-within伪类替代:focus,该伪类会在容器内部任意元素获得焦点时触发容器样式,完美匹配需求。同时保留:active伪类处理点击瞬间的状态。

修改后的关键CSS代码

/* 替换原有的.search-bar:active, .search-bar:focus */
.search-bar:active, .search-bar:focus-within {
    background-color: rgba(134, 131, 181, 0.3);
}

/* 替换原有的.search-bar:focus::placeholder */
.search-bar:focus-within::placeholder {
    color: rgba(67, 60, 60, 0.6);
}

完整修改后的搜索栏相关CSS片段

.search-bar {
    display: flex;
    border-radius: 30px;
    border: none;
    outline: none;
    height: 30px;
    width: 250px;
    margin: 15px;
    padding: 10px;
    background-color: rgba(236, 220, 220, 0.817);
    align-items: center;
    align-content: stretch;
    justify-content: center;
}

.search-bar input {
    border: none;
    outline: none;
    background: transparent;
    color: black;
    border-radius: inherit;
    padding: 8px;
    margin: 0; /* 修正原代码里的笔误"o"为"0" */
    color: inherit;
    flex: 1;
    overflow: hidden;
}

.search-bar:hover {
    background-color: rgba(255, 24, 81, .6);
}

.search-bar:active, .search-bar:focus-within {
    background-color: rgba(134, 131, 181, 0.3);
}

.search-bar:hover::placeholder {
    color: rgba(236, 220, 220, 0.817);
}

.search-bar:focus-within::placeholder {
    color: rgba(67, 60, 60, 0.6);
}

.search-bar button {
    border-radius: inherit;
    width: 30px;
    height: 30px;
    border: none;
    outline: none;
    padding: 0;
    margin: 0;
    background: transparent;
    overflow: hidden;
    cursor: pointer;
}

.search-bar img {
    width: 17px;
    height: 17px;
}

HTML部分无需修改,保持原有结构即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:01:08