网站首页 > 知识剖析 正文
要实现一个搜索框始终固定在页面顶部,无论用户如何滚动页面,可以使用CSS的position: fixed;属性。fixed定位会使元素相对于浏览器窗口定位,而不是相对于父元素。这使得元素在页面滚动时保持固定位置。
.search {
position: fixed; /* 相对于浏览器窗口定位 */
top: 0; /* 顶部距离为0 */
left: 50%; /* 水平居中 */
transform: translateX(-50%); /* 水平居中修正 */
z-index: 2; /* 确保搜索框显示在其他元素之上 */
display: flex; /* 使用 Flex 布局 */
align-items: center; /* 垂直居中 */
background-color: white; /* 背景颜色 */
padding: 10px; /* 内边距 */
border-radius: 23px; /* 圆角 */
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); /* 阴影效果 */
width: 80%; /* 设置宽度 */
max-width: 600px; /* 最大宽度 */
}
说明
- position: fixed;:使元素相对于浏览器窗口定位,而不是相对于父元素。
- top: 0;:将搜索框固定在页面顶部。
- left: 50%; 和 transform: translateX(-50%);:水平居中搜索框。
- z-index: 2;:确保搜索框显示在其他元素之上。
- background-color: white;:设置背景颜色。
- padding: 10px;:设置内边距。
- border-radius: 23px;:设置圆角。
- box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);:设置阴影效果,使搜索框看起来更美观。
- width: 80%; 和 max-width: 600px;:设置搜索框的宽度。
完整示例
假设你的HTML结构如下:
html
深色版本
1<div class="search">
2 <form @submit.prevent="performSearch">
3 <input v-model="searchKeyword" placeholder="输入搜索关键字" />
4 <button type="submit">搜索</button>
5 </form>
6</div>
7
8<!-- 其他内容 -->
猜你喜欢
- 2025-07-14 css中 background position(css background)
- 2025-07-14 css设置div只显示某一边的边框(css每个div给个边框)
- 2025-07-14 一文说透CSS变量(css var变量)
- 2025-07-14 CSS view():JavaScript 滚动动画的终结
- 2025-07-14 盘点CSS中5个让你“怀疑人生”的“垂直居中”解决方案
- 2025-07-14 那些年我总结的css水平垂直居中(css 水平居中 垂直居中 水平垂直居中)
- 2025-07-14 CSS position属性sticky实现吸顶菜单效果
- 2025-07-14 2024-2025年最新CSS特性:新功能和令人兴奋的变化
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)