如何通过CSS为HTML中多张图片设置不同尺寸?
Ah, I totally get where you're coming from—this is a super common specificity gotcha that trips up a lot of folks when they're starting out with CSS. Let's break down why your inline HTML width/height attributes aren't working, then walk through a few clean, maintainable solutions.
Why Your Current Approach Isn't Working
The core issue here is CSS specificity priority. Your global img selector is a CSS rule, and browsers prioritize CSS declarations over the old-school HTML width/height attributes. So even though you added those attributes to myimg2.png, the broader CSS rule for all img elements is overriding them.
Solution 1: Use CSS Classes (Recommended)
This is the cleanest, most scalable approach. Assign unique classes to your images, then target those classes in your CSS to override the base style.
HTML
<img src="assets/image/myimg1.png" class="image-banner" /> <img src="assets/image/myimg2.png" class="image-icon" />
CSS
/* Base default style for most images */ img { width: 212px; height: 95px; } /* Override for specific image types */ .image-banner { /* Keep the base style here, or adjust if needed */ width: 212px; height: 95px; } .image-icon { width: 65px; height: 72px; }
Classes are ideal because you can reuse them across multiple images if you have others that need the same size, and it keeps your styles organized.
Solution 2: Use Inline style Attributes
If you only need to adjust a one-off image and don't want to add a class, use the inline style attribute instead of HTML's native width/height. The style attribute has higher specificity than global element selectors, so it will reliably override your base img rule.
HTML
<img src="assets/image/myimg1.png" /> <img src="assets/image/myimg2.png" style="width: 65px; height: 72px;" />
Solution 3: Target Specific Images by Source (Not Recommended)
You can target an image directly by its src attribute, but this is fragile—if you ever change the image file path, the CSS rule will break. Use this only as a last resort:
CSS
img { width: 212px; height: 95px; } img[src="assets/image/myimg2.png"] { width: 65px; height: 72px; }
A Quick Note on !important
You might see people suggest adding !important to force a rule to override others, like this:
img[src="assets/image/myimg2.png"] { width: 65px !important; height: 72px !important; }
But avoid this whenever possible—it makes your CSS harder to debug and maintain down the line. Stick to classes or inline styles instead for cleaner, more predictable code.
内容的提问来源于stack exchange,提问作者user11137294

