如何用CSS实现搜索按钮与搜索框并排居中?
实现搜索框与按钮并排居中的解决方案
你的代码里有两个关键问题导致无法实现并排居中:
- 搜索输入框和按钮都设置了
display: block,这会强制它们各自独占一行; - 包裹表单的
<div>没有添加你写好的search-container类,导致容器的居中样式没生效。
下面提供两种可行的修改方案:
方案一:使用inline-block调整
修改后的HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Best Cookies: Buy the best chocolate cookies!</title> <link href="style.css" rel="stylesheet" type="text/css"> </head> <body> <!--This is the website header--> <h1 id="Cookieland">Cookieland</h1> <div class="search-container"> <form action="#"> <input type="text" class="search-input" placeholder="Search Cookies"> <button type="submit" class="search-button">Search</button> </form> </div> </body> </html>
修改后的CSS代码
h1 { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: black; text-align: center; background-color: wheat; height: 70px; padding: 0px; margin: auto; } body { background-color:black; } /* Styling for the search container */ .search-container { text-align: center; margin-top: 20px; } /* Styling for the search input */ .search-input { padding: 10px; border-radius: 20px; border: 2px solid #ccc; width: 400px; margin-right: 8px; /* 给输入框加右边距,避免和按钮贴紧 */ } /* Styling for the search button */ .search-button { padding: 10px 20px; border-radius: 20px; border: 2px solid #ccc; background-color: #f0f0f0; color: #333; cursor: pointer; transition: background-color 0.3s; } /* Styling for the search button on hover */ .search-button:hover { background-color: #e0e0e0; }
方案二:使用Flex布局(更推荐)
Flex布局是现代前端常用的布局方式,代码更简洁,适配性更强。
修改后的CSS代码(HTML和方案一相同)
h1 { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: black; text-align: center; background-color: wheat; height: 70px; padding: 0px; margin: auto; } body { background-color:black; } /* Styling for the search container */ .search-container { display: flex; justify-content: center; /* 水平居中容器内的元素 */ gap: 8px; /* 直接控制输入框和按钮的间距 */ margin-top: 20px; } /* Styling for the search input */ .search-input { padding: 10px; border-radius: 20px; border: 2px solid #ccc; width: 400px; } /* Styling for the search button */ .search-button { padding: 10px 20px; border-radius: 20px; border: 2px solid #ccc; background-color: #f0f0f0; color: #333; cursor: pointer; transition: background-color 0.3s; } /* Styling for the search button on hover */ .search-button:hover { background-color: #e0e0e0; }
说明
- 方案一中,
display: inline-block让元素在同一行显示,同时保留块级元素的宽高特性; - 方案二中,Flex布局通过
justify-content: center实现水平居中,gap属性可以轻松控制元素间的间距,无需手动设置margin,更易维护。
内容的提问来源于stack exchange,提问作者user23742144
相关产品推荐
相关产品推荐

