如何在图片下方添加轮廓矩形(效果如图所示)
Hey there! No worries at all—we all start somewhere, and this is a totally common styling task to tackle. Let me walk you through two straightforward ways to add that outline rectangle below your image, whether it's a JPEG or a CSS-drawn shape.
The cleanest way to do this without cluttering your HTML is using a container and CSS pseudo-elements. Here's a complete, tweakable example:
<div class="image-container"> <img src="your-image.jpg" alt="Description of your image"> </div>
.image-container { /* Lets us position the outline relative to the image container */ position: relative; /* Optional: Center the container on the page */ margin: 2rem auto; max-width: 300px; /* Adjust to match your image's ideal width */ } .image-container img { width: 100%; height: auto; /* Ensures the image sits on top of the outline */ position: relative; z-index: 1; } /* This pseudo-element creates the outline rectangle */ .image-container::after { content: ""; position: absolute; bottom: -12px; /* Push the outline below the image */ left: 8px; /* Shift it left from the image edge */ right: 8px; /* Shift it right from the image edge */ height: 30px; /* Height of your outline rectangle */ border: 2px solid #333; /* Outline style - adjust width/color as needed */ background-color: transparent; /* Keep it hollow, or add a color here */ z-index: 0; /* Make sure the outline stays behind the image */ }
Play around with values like bottom, left, right, and border-color to match the exact look you're going for. For example, make the outline wider by reducing the left/right values, or change the border to a dashed style with border-style: dashed.
If you're working with a shape made entirely in CSS (like a circle, rounded square, or custom polygon), the approach is nearly identical—just wrap your shape in a container and reuse the pseudo-element trick:
<div class="shape-container"> <div class="css-shape"></div> </div>
.shape-container { position: relative; margin: 2rem auto; width: 300px; } .css-shape { width: 100%; height: 200px; background-color: #4285F4; border-radius: 10px; /* Example rounded corners for the shape */ position: relative; z-index: 1; } .shape-container::after { content: ""; position: absolute; bottom: -12px; left: 8px; right: 8px; height: 30px; border: 2px solid #333; background-color: transparent; z-index: 0; }
This works for any CSS-drawn shape—just adjust the .css-shape styles to create your desired form, and the outline will adapt to the container's size.
The best part about using pseudo-elements is that you keep your HTML clean while getting full control over the visual effect.
内容的提问来源于stack exchange,提问作者Diogo Ferreira

