如何实现box div响应式水平居中并优化网页响应式适配效果
解决方案
1. 类名为box的div响应式水平居中实现
修改原有.box的CSS规则即可:
.box { max-width: 1000px; width: 100%; margin: 0 auto; }
规则说明:
- 用
max-width替代原有的固定width,保证大屏幕下容器宽度最大为1000px,小屏幕下自动占满可用宽度 margin: 0 auto实现左右边距自动相等,完成水平居中效果
2. 网页整体响应式适配调整
你当前页面无响应式表现主要有两个核心问题,按以下步骤修改:
步骤1:添加viewport适配标签
在HTML文件的<head>标签内加入移动端适配基础配置:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
该标签会告诉浏览器以设备实际宽度渲染页面,不会默认缩放为PC端宽度。
步骤2:调整搜索框固定宽度
原有输入框固定600px宽度会在小屏幕下溢出,修改input[type="text"]的CSS规则:
input[type="text"] { background: #fff; max-width: 600px; width: calc(100% - 110px); height: 50px; padding: 0 10px; border: none; outline: none; border-radius: 25px 0 0 25px; font-size: 15px; }
用calc(100% - 110px)动态计算输入框宽度,自动适配容器剩余空间,不会出现横向溢出。
可选小屏幕优化
如果需要在500px以下的小屏设备上显示更友好,可以新增媒体查询规则:
@media (max-width: 500px) { body { margin: 15px; font-size: 16px; } h1 { margin-top: 50px; font-size: 24px; } button { width: 90px; font-size: 18px; } input[type="text"] { width: calc(100% - 90px); } }
修改后完整代码
完整CSS代码
body { background-color: rgb(231, 59, 59); font-family: "Alata"; font-size: 20px; margin: 30px; } h1 { margin-top: 100px; color: #202124; text-align: center; } .box { max-width: 1000px; width: 100%; margin: 0 auto; } input { position: relative; display: inline-block; box-sizing: border-box; } input[type="text"] { background: #fff; max-width: 600px; width: calc(100% - 110px); height: 50px; padding: 0 10px; border: none; outline: none; border-radius: 25px 0 0 25px; font-size: 15px; } button { left: -5px; position: relative; border-radius: 0 25px 25px 0; width: 110px; height: 50px; border: none; outline: none; cursor: pointer; background: #ffc170; color: #fff; font-size: 21px; } @media (max-width: 500px) { body { margin: 15px; font-size: 16px; } h1 { margin-top: 50px; font-size: 24px; } button { width: 90px; font-size: 18px; } input[type="text"] { width: calc(100% - 90px); } }
完整HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>搜索页面</title> <!-- 这里引入你的CSS文件 --> </head> <body> <h1>This is my page title...</h1> <div class="box"> <form> <input type="text" name="" placeholder="Search here" /> <button type="button">Search</button> </form> </div> </body> </html>
内容的提问来源于stack exchange,提问作者Aysha
相关产品推荐
相关产品推荐

