2024-05-17 css 绝对定位让父元素和子元素的高相同

2024-05-16  本文已影响0人  半眼鱼

要使得父元素和子元素的高度相同,可以通过设置父元素为相对定位,子元素为绝对定位,并且设置子元素的高度来实现。如果子元素的高度未知,可以通过设置父元素的padding-bottom为100%,子元素的height为0,再加上padding-bottom为实际的高度值,来实现高度同步。

以下是一个示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Parent-Child Height Equal</title>
<style>
  .parent {
    position: relative;
    width: 200px;
    height: 100px;
    background-color: lightblue;
    padding-bottom: 100%; /* 使用padding-bottom来撑起父元素的高度 */
  }

  .child {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    height: 0; /* 子元素高度设置为0 */
    padding-bottom: 50%; /* 子元素的padding-bottom为实际高度的一半 */
    background-color: lightcoral;
  }
</style>
</head>
<body>
<div class="parent">
  <div class="child"></div>
</div>
</body>
</html>

在这个例子中,父元素.parent的padding-bottom设置为100%,这会使得父元素的底部与其高度相同。子元素.child的padding-bottom设置为50%,这是因为它的高度是父元素高度的一半。这样,子元素和父元素的高度就会相同。

上一篇 下一篇

猜你喜欢

热点阅读