重叠CSS中相对定位的元素

时间:2018-11-26 14:30:36

标签: css sass

我试图仅使用CSS重叠两个元素。

到目前为止,我已经找到了一种方法。但是,我想知道是否还有其他/更好的方法来实现这一目标。

我发现的唯一方法是,将两个元素垂直移近时,是从底部元素减去底部边距。这是为了解决剩余的空间-然后从上部元素减去相同的边距以将其向下移动。我以前从未使用过这种方法,所以我想知道这是否是实现这种重叠效果的最佳方法吗?

body {
 width: 100%;
 height: 100%;
 background: lightgrey;
}

.bottom, .top{
  width: 20%;
  padding-bottom: 20%;
}

.top {
  background: blue;
  margin-bottom: -250px;
}

.bottom {
  padding-top:250px;
  margin-bottom: -250px;
  background: red;
  overflow: hidden;
  border-top-left-radius: 50%;
  border-top-right-radius: 50%;
}
<div class="top"></div>
<div class="bottom"></div>

2 个答案:

答案 0 :(得分:0)

html, body {
  margin: 0;
  padding: 0;
}

.parent {
  position: relative;
  width: 20%;
}

.child {
  height: 200px;
  background-color: blue;
}

.child--foreground {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: red;
  border-radius: 30px;
}
<div class="parent">
  <div class="child child--background">
    Background
  </div>
    <div class="child child--foreground">
    Foreground
  </div>
</div>

如果您尝试将元素放置在另一个元素上,我认为您应该使用定位https://css-tricks.com/almanac/properties/p/position/

答案 1 :(得分:0)

我认为这更简单

    body {
     width: 100%;
     height: 100%;
     background: lightgrey;
    }
   .bottom, .top{
     width: 20%;
     padding-bottom: 20%;
   }
   .top {
     background: blue;
   }
   .bottom { 
     background: red; 
     border-radius: 50% 50% 0 0;
     padding-top: 250px;
     transform: translateY(-50%);
   }
<div class="top"></div>
<div class="bottom"></div>