In css, how to use sub-parents to realize that a box is nested in another box and the nested box is centered!

To nest a child box in a parent box in CSS, make the child box absolutely positioned relative to the parent box, and then center the nested child box, you can follow the steps below:

1. Create an HTML structure of a parent box and a child box.
2. Use CSS to set the parent box to relative positioning (`position: relative;`).
3. Set the child box to absolute positioning (`position: absolute;`).
4. Use `top`, `left`, `right`, `bottom` properties to adjust the position of the child box within the parent box to achieve a centering effect.

Here is an example:

<!DOCTYPE html>
<html>
<head>
<style>
  .parent {
    width: 300px;
    height: 200px;
    background-color: lightgray;
    position: relative; /* 父盒子相对定位 */
  }

  .child {
    width: 100px;
    height: 100px;
    background-color: coral;
    position: absolute; /* 子盒子绝对定位 */
    top: 50%; /* 相对于父盒子的上边缘向下移动 50% */
    left: 50%; /* 相对于父盒子的左边缘向右移动 50% */
    transform: translate(-50%, -50%); /* 通过负偏移来使子盒子居中这是关键 */
  }
</style>
</head>
<body>

<div class="parent">
  <div class="child">
    <!-- 这里是子盒子的内容 -->
  </div>
</div>

</body>
</html>

Guess you like

Origin blog.csdn.net/qq_58647634/article/details/132203906