CSS图片居中失效求助:已尝试margin与display属性仍无效
Let’s break down the issues in your CSS that are stopping the image from centering, then fix them step by step:
1. width: 100% makes auto margins useless
When you set width: 100% on the image, it takes up the entire width of its parent container. margin: 0 auto only works to center elements when they have a width smaller than their parent—there’s no extra horizontal space left to distribute with auto margins here.
2. padding: 20px breaks the box model (by default)
By default, padding adds to an element’s total width. Even if you reduced the image’s width, that 20px padding would make the image wider than you expect, either pushing it out of the container or still preventing centering.
3. Parent container context (hidden in your code)
Your .card-header element might have unlisted styles (like float, position: absolute, or no defined width) that interfere with centering. We’ll account for that in the fixes below.
Fixed CSS Code
.card-header img { /* Replace 100% with a smaller width (e.g., 80% or a fixed px value) */ width: 80%; height: auto; padding: 20px; margin: 0 auto; display: block; /* Ensure padding is included in the image's total width */ box-sizing: border-box; } .banner-banner { display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; margin-right: 0; margin-left: -5px; background: linear-gradient(to bottom, #230343 0%, #A558F1 100%); }
Alternative Fix (If You Want Full-Width Image With Padding)
If you need the image to stay full-width but have padding around it, move the padding to the parent .card-header instead:
.card-header { padding: 20px; } .card-header img { width: 100%; height: auto; margin: 0 auto; display: block; }
Quick Check
Make sure .card-header doesn’t have float: left/right or position: absolute—these styles break block-level centering. If it does, add clear: both to .card-header or adjust its positioning.
内容的提问来源于stack exchange,提问作者mobile legends gaming pro

