插件窝 干货文章 如何用CSS实现两个子div在父div中重叠并居中?

如何用CSS实现两个子div在父div中重叠并居中?

容器 个子 div 居中 661    来源:    2025-03-19

要实现两个子 div 在父 div 中重叠并居中,可以使用 CSS 的 position 属性和 transform 属性。以下是一个示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Overlapping Divs</title>
    <style>
        /* 父容器样式 */
        .parent {
            position: relative;
            width: 300px;
            height: 200px;
            background-color: #f0f0f0;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        /* 子容器样式 */
        .child {
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: #ffcc00;
            border: 2px solid #000;
        }

        /* 第二个子容器样式 */
        .child2 {
            background-color: #00ccff;
            transform: translate(-50%, -50%);
        }
    </style>
</head>
<body>
    <div class="parent">
        <div class="child"></div>
        <div class="child child2"></div>
    </div>
</body>
</html>

解释:

  1. 父容器 (parent):

    • position: relative;:设置父容器为相对定位,以便子元素可以使用绝对定位相对于父容器进行定位。
    • widthheight:设置父容器的宽度和高度。
    • display: flex; justify-content: center; align-items: center;:使用 Flexbox 将子元素居中。
  2. 子容器 (child):

    • position: absolute;:设置子容器为绝对定位,使其可以相对于父容器进行定位。
    • widthheight:设置子容器的宽度和高度。
    • background-colorborder:设置子容器的背景颜色和边框。
  3. 第二个子容器 (child2):

    • transform: translate(-50%, -50%);:将第二个子容器向左和向上移动自身宽度和高度的一半,使其与第一个子容器重叠并居中。

结果:

  • 两个子 div 会在父 div 中重叠并居中显示。
  • 第一个子 div 是黄色的,第二个子 div 是蓝色的,并且它们会重叠在一起。

你可以根据需要调整父容器和子容器的大小、颜色等样式。