HTML/CSS新手求教:如何无需固定左margin实现图片居中
问题解决思路
你代码里的问题主要出在flex布局配置和容器宽度设置上,按以下步骤修改即可实现预期的居中效果:
- 首先调整外层容器的宽度适配:你当前给
#top-stories设置了固定1000px宽度,小屏幕下会出现横向滚动条,改成最大宽度限制可适配不同尺寸的设备 - 补充flex主轴对齐规则:flex布局默认沿主轴(水平方向)左对齐,增加
justify-content: center配置就能让内部的文章卡片整体在容器内水平居中 - (可选)如果需要文章卡片内部的标题、文本也居中,给
article标签增加text-align: center属性即可 - 额外注意:
@import导入字体的语句必须放在CSS所有规则的最顶部,否则部分浏览器会无法识别加载外部字体
修改后的完整代码
CSS部分
/* 字体导入必须放在最顶部 */ @import url('https://fonts.googleapis.com/css2?family=Bonheur+Royale&display=swap'); body { background: #ffffff; color:#000; font-family: "Bonheur Royale" ,cursive ; margin: 0px } h3{ color: #000 } body h1 { font-weight: 300; margin: 20px 30px; } #main-header { border-bottom:3px solid #000; } #top-stories { max-width: 1000px; /* 替换原固定width */ width: 100%; /* 新增,小屏幕占满宽度 */ margin:auto; margin-top: 20px; display: flex; align-items: center; justify-content: center; /* 新增,主轴居中 */ } article { max-width: 33%; border: 1px solid #000; padding: 10px; margin: 10px; /* text-align: center; 可选,开启后内部文字居中 */ } .article-image { height: 200px; width: 100%; background-size: cover !important; background-position: center !important; }
HTML部分无需修改,原有代码即可正常运行
<header id="main-header" > <h1>Welcome in my new page! </h1> </header> <main> <section id="top-stories"> <article> <div class="article-image" style="background:url(/Users/jozefdzogan/Desktop/atom/images/iu.jpeg)"> </div> <h3> Dog </h3> <p> Text abou some dog i dont know </p> </article> <article> <div class="article-image" style="background:url(/Users/jozefdzogan/Desktop/atom/images/1344352035229.jpg)"></div> <h3> My old helmet </h3> <p>Some text goes in here </p> </article> <article> <div class="article-image" style="background:url(/Users/jozefdzogan/Desktop/atom/images/23289271.jpg)"></div> <h3> AIC steelwork <a href="#">More </a> now </h3> <p> html </p> </article> </section> </main>
内容的提问来源于stack exchange,提问作者usernumerouno
相关产品推荐
相关产品推荐

