首页顶部固定背景图不显示及文字层叠问题求助
Hey sadnoodle, let's work through the problems you're facing with your homepage cover photo and text—this is a common setup, so we'll get it sorted quickly!
1. Why Your Background Image Isn't Showing Up
Your first mistake was using the non-standard image() function in CSS; the correct way to reference background images is with url(). Then in your updated code, you used HTML escape characters (") in your CSS and HTML, which isn't needed here—stick to regular quotes instead. Also, double-check your file path to make sure it points correctly to your image file relative to your CSS file.
For example, if your project structure looks like this:
your-project/ ├── css/ │ └── styles.css ├── images/ │ └── homepage/ │ └── Dark_Eventide_Flipped_2500.jpg └── index.html
Your CSS path should use ../ to go up one level from the css folder to reach the images folder.
2. Fixing Text Position & Overflow
Right now, your container only has the height of your h1 text, which is why the background image might look cut off and your text isn't positioned properly. We'll add a minimum height to the container and use flexbox to center your text perfectly over the image.
Corrected CSS
/*CSS Code for Cover Photo*/ .home-bg-cover-photo { background-image: url("../images/homepage/Dark_Eventide_Flipped_2500.jpg"); margin: -10px; background-repeat: no-repeat; background-position: center top; background-size: cover; /* Use cover for better scaling than 100%, auto */ min-height: 500px; /* Adjust this to match your image's height */ display: flex; align-items: center; /* Vertically center text */ justify-content: center; /* Horizontally center text */ padding: 20px; /* Add padding so text doesn't touch edges on small screens */ } /* Style the text to stand out against the background */ .home-bg-cover-photo h1 { color: white; text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.8); margin: 0; }
Corrected HTML
<!DOCTYPE html> <html lang="en"> <head> <link href="css/styles.css" rel="stylesheet"> </head> <body> <div class="home-bg-cover-photo"> <h1> Hi, I'm sadnoodle. </h1> <!--This is the text that appears on top of BG photo --> </div> </body> </html>
Key Notes
background-size: coverensures your image scales to fill the container without stretching, cropping only as needed.- Flexbox makes centering text straightforward—no need for
z-indexhere because the text is a direct child of the container, so it will naturally sit on top of the background image. - The text shadow helps make your heading readable even if your background image has bright areas.
内容的提问来源于stack exchange,提问作者sadnoodle

