You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用CSS和HTML创建指定盒子布局?Web开发新手求助

Fixing Your Box Layout

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: relative to .grey: This tells the browser that any child elements with position: absolute should be positioned relative to this grey box, not the entire page.
  • Added position: absolute to .pink: This lets us use top, right, bottom, or left to place the box precisely. top: 0 and right: 0 sticks it directly to the top-right corner.
  • Fixed the z-index: Since .pink now 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:41:17