如何缩小container类宽度并将页面内容居中?附代码示例
解决方案
1. 让所有内容居中显示
给body添加flex布局,实现整体内容水平居中,同时保证页面占满视口高度避免内容贴顶:
body { font-family: Helvetica; background-color: #000000; color: white; display: flex; flex-direction: column; align-items: center; min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box; }
给头部和内容容器设置最大宽度,防止大屏幕上内容拉得太宽:
#header, .boxes { width: 100%; max-width: 600px; text-align: center; /* 让头部文字也居中 */ }
2. 缩小.container宽度
默认flex容器会占满父元素宽度,给.container设置宽度限制,再用auto左右margin让它自身居中:
.container { display: flex; justify-content: space-evenly; align-items: center; background-color: #5A5A5A; color: white; padding: 10px 0; /* 添加上下内边距,避免内容贴边 */ margin: 5px auto; /* 实现水平居中 */ border-radius: 5px; width: 80%; /* 可按需调整,也可以用max-width: 400px或width: fit-content */ }
完整修改后的代码
CSS 部分
body { font-family: Helvetica; background-color: #000000; color: white; display: flex; flex-direction: column; align-items: center; min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box; } #header, .boxes { width: 100%; max-width: 600px; text-align: center; } .container { display: flex; justify-content: space-evenly; align-items: center; background-color: #5A5A5A; color: white; padding: 10px 0; margin: 5px auto; border-radius: 5px; width: 80%; } #clickMe { border: 1px solid white; display: inline-block; padding: 10px; font-family: Helvetica; border-radius: 3px; margin-top: 20px; /* 和上方内容拉开距离 */ }
HTML 部分(修正了p标签闭合问题)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>List of items</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="header"> <h1>Products</h1> <p>______</p> </div> <div id="appendToMe"> <div class="boxes"> <div class="container"> <p>Hello</p> <p>World</p> <p>Hello</p> </div> <div class="container"> <p>Hello</p> <p>World</p> <p>Hello</p> </div> <div class="container"> <p>Hello</p> <p>World</p> <p>Hello</p> </div> </div> </div> <div id="clickMe">Toggle Dark Mode</div> </body> </html>
核心说明
- 利用
body的flex布局实现整体内容居中,同时min-height: 100vh保证页面高度足够,不会出现内容贴顶的情况。 .container通过设置宽度+auto左右margin,既限制了自身宽度,又实现了在父容器内的水平居中,宽度值可根据需求自由调整为百分比、固定值或fit-content(适配内容宽度)。- 给
#header和.boxes设置max-width,保证大屏幕上内容不会过度拉伸,维持紧凑的视觉效果。
内容的提问来源于stack exchange,提问作者Brad
相关产品推荐
相关产品推荐

