如何在视差图像容器旁正确定位标题与段落文本块?
问题根因
- 全局布局规则错误:你给
html和body设置了display: flex,flex默认主轴为水平方向,所有直接子元素(.image-container、.text、.paragraph)会横向排列,你又给.image-container设置了width: 100%,直接占满了整个视口宽度,剩下的文本块可用宽度被压缩到近乎为0,文字就会显示为竖直的细直线。 - 段落容器高度设置不合理:
.paragraph类固定了height: 50px,但你使用了30px的字号,300px宽度下这段文本至少需要数百像素高度才能完全展示,固定高度过小导致文字溢出挤压变形。 - 定位逻辑混乱:你通过
left、top相对定位硬挪元素位置,没有统一的文本容器做布局基准,不仅适配性差,还容易出现位置偏移。
修复方案
1. HTML结构调整
把标题和段落放到统一的文本容器中,和视差图片容器平级:
<!DOCTYPE html> <html> <head> <title>"Parallax Astro Girl"</title> <link rel="stylesheet" type="text/css" href="./styles.css"/> <meta name="author" content="AS"> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> </head> <body> <div class="image-container"> <canvas class="canvas" width="2198" height="2993" id="canvas"></canvas> <div class="loading-screen" id="loading">loading...</div> </div> <!-- 新增统一文本容器 --> <div class="text-wrapper"> <div class="text"> <h1>Astro Girl</h1> </div> <div class="paragraph"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas quis elit lectus. Aliquam erat volutpat. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec consequat sapien et nisl sodales tempor. In eu nunc sed mauris elementum congue. Praesent libero neque, mattis vitae posuere sed, accumsan vel est. Nunc eu pellentesque magna. Maecenas convallis eros orci, quis convallis justo posuere a. Nam vitae suscipit ipsum.</p> </div> </div> </body> <script type="text/javascript" src="./tween.js"></script> <script type="text/javascript" src="./main.js"></script> </html>
2. CSS样式调整
html, body { box-sizing: border-box; margin: 0; height: 100%; background: black; display: flex; /* 子元素垂直居中对齐 */ align-items: center; /* 子元素两边留出间距 */ justify-content: space-around; font-family: sans-serif; overflow: hidden; } .text h1 { padding: 0 0 20px 0; color: white; font-size: 70px; white-space: nowrap; margin: 0; } .paragraph { color: white; width: 300px; font-size: 16px; line-height: 1.6; } .text-wrapper { /* 给文本容器设置最小宽度,避免被挤压 */ min-width: 300px; } .image-container { display: flex; height: 100%; max-width: 60%; position: relative; -webkit-perspective: 1500px; perspective: 1500px; } .canvas { width: auto; max-height: 100%; max-width: 100%; display: block; margin: auto; } .loading-screen { position: absolute; width: 100%; height: 100%; background: black; top: 0; bottom: 0; left: 0; right: 0; visibility: visible; opacity: 1; text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center; line-height: 40px; transition: 0.25s ease all 0.75s; color: #999; transform: translateZ(50px); } .loading-screen.hidden { visibility: hidden; opacity: 0; }
如果需要调整字号、文本宽度、元素间距,可以直接修改对应参数即可。
内容的提问来源于stack exchange,提问作者98SSVM
相关产品推荐
相关产品推荐

