CSS中background-repeat: no-repeat属性不生效问题排查求助
background-repeat: no-repeat working for your .mtl container? Hey there! Let's break down what's going wrong here and fix it step by step.
1. The first issue: Incorrect CSS selector syntax
You wrote *.mtl as your class selector, but the correct way to target elements with the mtl class is simply .mtl. While *.mtl is technically valid (it means "all elements with the mtl class"), adding the wildcard * here is unnecessary and can lead to unexpected style cascading behavior with your global * selector.
2. The second issue: Global background-size: cover overriding your intended behavior
Your global * selector sets background-size: cover, which applies to every element on the page—including your .mtl div. When background-size: cover is active, the browser automatically scales your background image to fill the entire container. Even if you set background-repeat: no-repeat, you won't see a difference because the image is already stretched to cover the whole space, leaving no room for repetition.
Here's the fixed CSS code:
* { margin: 0; padding: 0; background-color: wheat; /* Removed background-size: cover here to avoid affecting all elements */ } .mtl { height: 100vh; background-image: url("./images/mars_p.jpg"); background-repeat: no-repeat; background-position: -1844px 1160px; /* Optional: Set background-size to auto (default) or another value if needed */ background-size: auto; }
What changed:
- Fixed the class selector to
.mtlso your styles target the correct element properly. - Removed
background-size: coverfrom the global*selector, or explicitly setbackground-size: autoon.mtl—this lets yourbackground-repeat: no-repeatrule work as intended, since the image won't be forced to stretch and fill the entire container.
After making these changes, refresh your page and you should see the background image display without repeating, exactly as you intended.
内容的提问来源于stack exchange,提问作者Akki Jangir




