如何用CSS和HTML创建指定盒子布局?Web开发新手求助
Hey there! Awesome that you're diving into HTML & CSS at 13—keep up the amazing work! Let's break down how to get your box layout working the way you want.
What's Missing in Your Current Code?
Right now, your .pink box is stuck in the top-left corner of the grey box, and the z-index isn't doing anything at all. That's because z-index only works on elements that have a position property set (like relative, absolute, fixed, or sticky). Also, if you want the pink box to sit in a specific spot (like the top-right, center, or floating over the grey box), we need to add positioning rules to control its placement.
Example Solution (Positioning Pink in the Top-Right)
Here's a modified version of your code that positions the pink box in the top-right corner of the grey box, and makes sure the z-index behaves as expected:
CSS Code
.grey{ height: 300px; width: 700px; background-color: #e5e5e5; /* Add relative positioning so the pink box uses this as its reference */ position: relative; z-index: 0; } .pink{ height: 150px; width: 100px; background-color: #ff8a8a; /* Absolute positioning lets us place the box exactly where we want */ position: absolute; top: 0; right: 0; /* Now z-index works because we've set a position value */ z-index: 1; }
HTML Code
<div class="grey"> <div class="pink"> </div> </div>
What Did We Change?
- Added
position: relativeto.grey: This tells the browser that any child elements withposition: absoluteshould be positioned relative to this grey box, not the entire page. - Added
position: absoluteto.pink: This lets us usetop,right,bottom, orleftto place the box precisely.top: 0andright: 0sticks it directly to the top-right corner. - Fixed the z-index: Since
.pinknow has a position set, its z-index of 1 ensures it sits on top of the grey box (which has z-index 0).
Want a Different Layout?
If your target design is something else (like the pink box centered, or at the bottom-left), just adjust the positioning values. For example, to center the pink box perfectly:
.pink{ position: absolute; top: 50%; left: 50%; /* This moves the box back by half its own width/height to truly center it */ transform: translate(-50%, -50%); }
Don't be afraid to tweak numbers and experiment—that's one of the best ways to learn web dev! 😊
内容的提问来源于stack exchange,提问作者Hamza

