HTML/CSS布局问题:首行70%+30%两列次行一列布局错位
解决首行70%/30%、第二行整列的Flex布局异常问题
你的代码核心问题是给所有带.div类的元素统一设置了flex-basis: 50%,导致前两个div各占50%宽度挤在第一行,完全不符合你要的70%/30%首行布局;同时未明确第三行元素的整行占比规则,加上margin的影响,最终出现布局偏移。
以下是修正后的完整代码:
CSS 代码
body { background-image: url("1.JPG"); background-repeat: repeat-x; } .wrapper { display: flex; flex-wrap: wrap; } .div1 { flex: 0 0 70%; /* 固定占70%宽度,不缩放 */ margin-left: 100px; color: white; box-sizing: border-box; /* 避免margin/padding破坏宽度设定 */ } .div2 { flex: 0 0 30%; /* 固定占30%宽度,不缩放 */ box-sizing: border-box; } .div3 { flex: 0 0 100%; /* 占满整行宽度 */ margin-left: 100px; box-sizing: border-box; }
HTML 代码
<div class="wrapper"> <div class="div1">Hi! <?php echo htmlspecialchars($_SESSION["username"]); ?> Welcome to HMIS</div> <div class="div2">hhhhh</div> <div class="div3"> <a href="bill.php" class="logo me-auto"><img src="assets/img/logo.png" width="100" height="60"></a> </div> </div>
关键修正说明
- 移除了原代码中
.div类的flex-basis: 50%统一设置,改用flex: 0 0 [宽度比例]的方式精准控制每个元素的宽度:flex: 0 0 70%表示元素不放大、不收缩,基础宽度为父容器的70%flex: 0 0 100%让第三行元素占满整行
- 添加
box-sizing: border-box确保元素的margin、padding不会超出设定的宽度,避免布局偏移 - 保留了你原有的margin和样式设置,仅调整布局核心规则
内容的提问来源于stack exchange,提问作者Student
相关产品推荐
相关产品推荐

