设置body margin为0后仍存在侧边空白(纯HTML和CSS)
问题解决:Hero Image侧边空白消除方案
核心问题定位
- CSS选择器错误:你写的
.body是类选择器,但目标是<body>标签,应该用body(不带点),否则样式根本没作用到body上。 - 未重置全局默认样式:浏览器默认会给
html标签添加少量margin/padding,只重置body不够。 - 无效CSS语法:
#home里的background-size:没有设置值,属于无效代码,建议删除。
修正后的代码
CSS部分
/* 重置全局默认边距,确保无空白 */ html, body { font-family: 'Times New Roman', Times, serif; margin: 0; padding: 0; box-sizing: border-box; /* 避免padding撑开元素宽度 */ } /* 修复导航栏可能的溢出问题 */ .navigation { margin: 0; overflow: hidden; width: 100%; /* 用100%代替100vw,避免横向滚动条 */ display: flex; align-items: center; justify-content: center; padding-bottom: 15px; } a { text-decoration: none; font-weight: light; } .navigation-inner { background: #eaeae4; border-radius: 5px; overflow: hidden; font-size: 28px; display: flex; } .notification-round { background: rgba(240,0,0,.6); color: white; padding: 0 8px; border-radius: 50%; font-size: 16px; margin-left: 3px; } .navigation-link { padding: 15px 20px 10px 20px; display: inline-block; color: rgba(0,0,0,.7); transition: all .2s ease-in-out; border-bottom: 4px solid transparent; } .navigation-link:hover { background: rgba(50,50,0,.1); border-bottom-color: #8acc84; } .navigation-link > i { padding-right: 8px; } /* HERO 部分 */ #home { /* 移除无效的background-size: 行 */ } .hero-image { background-image: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.1)), url("../images/furniture.jpg"); height: 400px; background-position: center; background-repeat: no-repeat; background-size: cover; position: relative; width: 100%; /* 确保宽度占满 */ } .hero-text { text-align: center; position: absolute; top: 25%; left: 50%; transform: translate(-50%, -50%); color: white; } .hero-text h1 { font-size: 50px; margin: 0; /* 移除标题默认margin,避免顶部空白 */ }
HTML部分(无需修改)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Bill's Furniture Emporium</title> <link rel="stylesheet" href="./css/one_page_website.css"> </head> <body> <!-- NAV --> <div class = "navigation"> <header class="navigation-shadow"> <div class = "navigation-inner"> <a href="#home" class="navigation-link" id="link">HOME</a> <a href="#gallery" class="navigation-link" >GALLERY</a> <a href="#contact" class="navigation-link" >CONTACT</a> </div> </header> </div> <!--HOMEPAGE--> <div id="home"> <div class="hero-image"> <div class="hero-text"> <h1>Bill's Furniture Emporium</h1> </div> </div> </div> </body> </html>
额外优化说明
- 用
width: 100%代替100vw:100vw会包含滚动条宽度,可能导致横向滚动,100%则是父容器的可用宽度,更安全。 - 添加
box-sizing: border-box:让元素的padding和border不会撑开宽度,避免意外溢出。 - 移除
h1的默认margin:防止标题上方出现不必要的空白。
内容的提问来源于stack exchange,提问作者Brandon Marshall
相关产品推荐
相关产品推荐

