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

React+CSS搜索栏组件内部间隙消除问题求助

问题描述

按照YouTube教程制作了一个Search Bar组件,但input元素与form容器之间存在较大间隙。已核对CSS类名,确定需要调整search__input元素来解决该CSS问题,附上相关React及CSS代码:

React代码

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faMagnifyingGlass } from "@fortawesome/free-solid-svg-icons"
import "./SearchBar.css"

const SearchBar = ({ posts, setSearchResults }) => {
    const handleSubmit = (e) => e.preventDefault()

    const handleSearchChange = (e) => {
        if (!e.target.value) return setSearchResults(posts)

        const resultsArray = posts.filter(post => post.title.includes(e.target.value) || post.body.includes(e.target.value))

        setSearchResults(resultsArray)
    }

    return (
        <header>
            <form className="searchbar" onSubmit={handleSubmit}>
                <input
                    className="search__input"
                    type="text"
                    id="search"
                    onChange={handleSearchChange}
                />
                <button className="search__button">
                    <FontAwesomeIcon icon={faMagnifyingGlass} />
                </button>
            </form>
        </header>
    )
}
export default SearchBar

CSS代码

@import url("https://fonts.googleapis.com/css2?family=Nunito&display=swap");

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

input,
button {
  font: inherit;
}

html {
  font-size: 1rem;
}

body {
  background-color: #000;
  font-family: 'Nunito', sans-serif;
}

p {
  color: whitesmoke;
  margin-top: 0.5em;
}

article {
  margin: 1em;
  padding: 1em;
  background-color: midnightblue;
  color: whitesmoke;
  border-radius: 15px;
}

img {
  border-radius: 15px;
  display: block;
}

header {
  background-color: gold;
  padding: 1em;
  display: flex;
  justify-content: center;
  align-items: center;
}

.searchbar {
  width: 95%;
  border: 2px solid #000;
  border-radius: 2em;
  overflow: hidden;
  font-size: 1rem;
  display: flex;
  flex-flow: row nowrap;
}

.searchbar:focus-within {
  box-shadow: 2px 2px 5px #000;
}

.search__button,
.search__input {
  background-color: #fff;
  border: none;
  outline: none;
}

.search__input {
  /* padding: 1em; */
  width: 85%;
}

.search__button {
  width: 15%;
  font-size: 1.5rem;
  padding-right: 0.5em;
  color: gray;
  display: grid;
  place-content: center;
}
}

解决方案

1. 恢复search__input的垂直内边距

CSS中search__input的padding: 1em;被注释掉了,这是导致input与容器间出现间隙的核心原因。取消注释后,input会填充form容器的上下空间,消除间隙:

.search__input {
  padding: 1em; /* 取消此注释 */
  width: 85%;
}

2. 移除多余的闭合花括号

CSS代码最后一行多了一个无效的},会影响样式解析,直接删除即可:

/* 删除此行的多余 } */
}

补充说明

.searchbar采用flex布局,设置input的垂直padding后,flex会自动让input与button高度对齐,填满form容器内部空间,彻底解决间隙问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 13:13:14