首页 > 解决方案 > 如何在父 div 中包含边框形状?

问题描述

我正在尝试创建一个三角形,使其位于其父级内,其宽度为父级宽度的 100%。

这是我尝试过的:

* {
margin:0;
padding:0;
}

.test {
width: 500px;
height: 500px;
background-color: green;
position: relative;
box-sizing: border-box;
}

.triangle-topleft {
      width: 0;
      height: 0;
      border-top: 100px solid red;
      border-right: 100vw solid transparent;
      position: absolute;
      box-sizing: border-box;
    }
<div class="test">
  <div class="triangle-topleft"></div>
</div>

因此,如您所见,我在父级(绝对位置)中有子级 div。为什么三角形仍然从父项中消失?有没有办法让三角形的宽度为 100%?

这里的大多数答案都是关于box-sizing: border-box,但它不起作用。

任何人都知道如何解决这个问题,或者有没有比使用边框更好的方法来制作顶部三角形?

标签: css

解决方案


您的代码没有按照您的意愿行事:100vw不是父宽度,而是视口宽度。因此,预计该形状将增长到父边界之外。如果要将其保持在范围内,则需要将border-right宽度设置为500px

* {
margin:0;
padding:0;
}

.test {
width: 500px;
height: 500px;
background-color: green;
position: relative;
box-sizing: border-box;
}

.triangle-topleft {
      width: 0;
      height: 0;
      border-top: 100px solid red;
      border-right: 500px solid transparent;
      position: absolute;
      box-sizing: border-box;
    }
<div class="test">
  <div class="triangle-topleft"></div>
</div>

但是,这可能很麻烦,因为这意味着您需要将父宽度硬编码为border-right-width. 另一种解决方案是简单地使用 CSS 线性渐变:

* {
  margin: 0;
  padding: 0;
}

.test {
  width: 500px;
  height: 500px;
  background-color: green;
  position: relative;
  box-sizing: border-box;
}

.triangle-topleft {
  width: 100%;
  height: 100px;
  position: absolute;
  background-image: linear-gradient(to bottom right, red 50%, transparent 50%);
}
<div class="test">
  <div class="triangle-topleft"></div>
</div>


推荐阅读