如何使用CSS为屏幕两侧添加边框?已尝试div和aspect-ratio无效
实现屏幕两侧边框的解决方案
步骤1:搭建基础HTML结构
保留你的核心元素,补充完整HTML文档结构:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>侧边边框效果</title> <style> /* 后续写入CSS样式 */ </style> </head> <body> <a>hello</a> </body> </html>
步骤2:添加固定侧边边框
用CSS固定定位实现始终悬浮在屏幕两侧的边框,这是适配需求的最优方案:
/* 重置默认样式,避免边距干扰 */ * { margin: 0; padding: 0; box-sizing: border-box; } /* 左侧边框 */ body::before { content: ''; position: fixed; top: 0; left: 0; width: 20px; /* 可自定义边框宽度 */ height: 100vh; /* 占满整个屏幕高度 */ background-color: #333; /* 可自定义边框颜色 */ } /* 右侧边框 */ body::after { content: ''; position: fixed; top: 0; right: 0; width: 20px; height: 100vh; background-color: #333; } /* 可选:给页面内容加左右内边距,防止被边框遮挡 */ body { padding: 0 30px; }
之前方法失效的原因
- 直接放置div但未设置
position: fixed:普通div会随页面滚动移动,无法固定在屏幕两侧 - 使用
aspect-ratio:该属性用于控制元素宽高比例,和固定侧边边框的需求完全不匹配,自然无法达到预期效果
内容的提问来源于stack exchange,提问作者tisme
相关产品推荐
相关产品推荐

