You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

首次开发网站遇背景叠加、矩形层居中定位问题该如何解决?

1

完整修改方案

以下是调整后的可直接运行的代码,实现边缘彩屑背景、中间内容块居中的效果,适配不同屏幕尺寸:

CSS代码

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

h1 {
  font-weight: 100;
  font-family: 'Pacifico', cursive;
  font-size: 70px;
  margin: 75px 0 40px 0;
  text-align: center;
}

p {
  font-family: 'Indie Flower', cursive;
  color: #222;
  font-size: 40px;
  line-height: 1.5;
}

body {
  background-image: url(images/confetti.jpg);
  background-size: cover;
  background-position: center;
  min-height: 100vh;
  padding: 40px 0;
}

div.background {
  width: 85%;
  max-width: 1200px;
  margin: 0 auto;
  /* 如果你需要的是白色背景,把下面的色值换成 #ffffff 即可 */
  background-color: #ffd7fa;
  padding: 20px 40px 60px 40px;
}

HTML代码

<!doctype html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="home.css">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Pacifico&display=swap" rel="stylesheet">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Indie+Flower&display=swap" rel="stylesheet">
</head>
<body>
  <div class="background">
    <h1>Spudgie Creations</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
      dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  </div>
</body>
</html>

核心调整说明

  • 全局样式重置消除了浏览器默认边距,避免布局错位
  • 所有内容统一放在.background容器内,仅需给这一个容器设置背景色即可,无需拆分多个独立块
  • 使用margin: 0 auto实现容器水平居中,百分比宽度加最大宽度的配置可以适配从手机到桌面的全尺寸设备,不会出现小屏幕内容溢出的问题
  • 给body设置上下内边距,保证内容块上下都能露出彩屑背景
  • 调整了p标签文字颜色,解决原代码中浅色背景上白色文字无法识别的问题

内容的提问来源于stack exchange,提问作者Spud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 03:06:03