如何用CSS实现section标签的边框颜色叠加效果?
Absolutely! You can totally recreate that layered border effect using only CSS—no extra <section> or <div> elements are required (though pseudo-elements will be your secret weapon here). Let’s build this out starting from your existing code, matching the style of the HTML & CSS Design and build websites cover.
How it works
We’ll use ::before and ::after pseudo-elements to create extra border layers. These act as "virtual" elements attached to your existing .boxed section, so you don’t need to clutter your HTML with extra markup. We’ll offset each layer slightly to create that stacked, overlapping look.
Updated Code
CSS
body{ background-color: #594451; color: #fff; min-height: 100vh; /* Ensure the page fills the viewport */ margin: 0; } h1 { position: relative; z-index: 10; /* Keep the title above all border layers */ text-align: center; padding-top: 2rem; } .boxed{ position: absolute; margin: auto; height: 20pc; width: 20pc; top: 0; right: 0; bottom: 0; left: 0; transform: rotate(45deg); } /* First border layer (your original style) */ .boxed::before { content: ''; position: absolute; inset: 0; /* Shorthand for top/right/bottom/left: 0 */ border-left: solid rgba(127, 203, 170, 1) 3pc; border-right: solid rgba(186, 179, 173, 1) 3pc; border-bottom: solid rgba(0, 171, 238, 1) 3pc; border-top: solid rgba(229, 99, 57, 1) 3pc; transform: translate(-1pc, -1pc); /* Shift this layer up-left */ z-index: -1; } /* Second overlapping border layer */ .boxed::after { content: ''; position: absolute; inset: 0; border-left: solid rgba(229, 99, 57, 0.8) 3pc; border-right: solid rgba(127, 203, 170, 0.8) 3pc; border-bottom: solid rgba(186, 179, 173, 0.8) 3pc; border-top: solid rgba(0, 171, 238, 0.8) 3pc; transform: translate(1pc, 1pc); /* Shift this layer down-right */ z-index: -2; }
HTML
<h1>Welcome to Rahul's Lab</h1> <section class="boxed"> <!-- Add your content here, just make sure to set a z-index to keep it above borders --> </section>
Customization Tips
- Adjust the
translate()values to make the layers more or less offset (try0.5pcfor a tighter stack, or2pcfor more separation). - Tweak the border colors and opacity (the
0.8in rgba) to match the cover’s muted, layered look. - If you want more than 2 layers, you can add a single nested
<div>inside.boxedand repeat the pseudo-element trick for that div—this lets you add 2 more layers without extra clutter.
This approach keeps your HTML clean and achieves exactly the overlapping border effect you’re aiming for, all with pure CSS.
内容的提问来源于stack exchange,提问作者rahulkesharwani

