首页 > 解决方案 > 用 CSS 制作的形状不断溢出父容器

问题描述

我正在制作一个小页面,我需要在背景中有 2 个形状(附设计截图)。我完全用 CSS 制作了它们。我已经为父容器尝试了 ::before/::after ,并且只是在 HTML 中单独的 DIV-s。问题是在这两种情况下,右下角的形状总是不断地离开容器并且出现滚动。我认为溢出会有所帮助,但它并没有为我做。谁能帮我解决这个问题?谢谢!

body {
  position: relative;
  min-height: 100vh;
  width: 100%;
  padding: 10%;
}

.container {
  width: 100%;
  margin: 1.5rem 0;
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: space-around;
}

.background-one {
  position: absolute;
  top: 0;
  left: -50%;
  background: linear-gradient(to top, $violet, $magenta);
  width: 375px;
  height: 54%;
  border-bottom-right-radius: 50%;
  border-bottom-left-radius: 50%;
  z-index: -1;
}

.background-two {
  position: absolute;
  bottom: 0;
  right: -50%;
  background: hsl(236, 72%, 63%);
  width: 375px;
  height: 54%;
  border-top-right-radius: 50%;
  border-top-left-radius: 50%;
  z-index: -1;
}
<body>
  <div class="background-one"></div>
  <div class="background-two"></div>

  <div class="container">
    <div class="phone"></div>
  </div>
</body>

我想要实现的目标没有任何溢出

发生什么了

标签: htmlcss

解决方案


好的,最后我想我找到了解决方案,以防万一有人遇到同样的问题。我已将这些 DIV(它们是背景形状)嵌套到另一个 DIV 中。我已经使容器 DIV 覆盖全屏,然后将这些形状 DIV 绝对定位到新容器,将容器的溢出设置为隐藏。

.newContainer {
  position: absolute;  //Its container is set to relative.
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.backgroundShape {
  position: absolute;
  bottom: 0;
  right: -50%;
  //other properties with width, height etc.
}

推荐阅读