css - 如何在父 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
,但它不起作用。
任何人都知道如何解决这个问题,或者有没有比使用边框更好的方法来制作顶部三角形?
解决方案
您的代码没有按照您的意愿行事: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>
推荐阅读
- r - 在 R 中使用魔法读取 svg 时出现失真
- docker - Docker 卷在容器行为中造成故障
- excel - 如何显示一个空控件所在页面的 msgbox?
- python - 如何阻止一串数字自发变化?
- python - 使用二进制搜索和递归搜索文本文件
- arrays - Scala - 两个数组的有效元素之和
- c# - 带有属性隐藏的 Swashbuckle XML 注释
- celery - 检查气流工作者(芹菜)上是否有正在运行的任务
- racket - 具有多个 ...s 的球拍语法模式
- python-3.x - 使用 pytest-asyncio 和 aiohttp 时“忽略异常:RuntimeError:事件循环已关闭”