A triangle in CSS that takes the whole width with a fixed height?

时间秒杀一切 提交于 2021-02-18 12:10:17

问题


I'm trying to make a triangle in CSS that takes the whole width of the parent with a fixed height.

I successfully did so with a linear-gradient like this:

.triangle {
    width: 100%;
    height: 120px;
    background: linear-gradient(to right bottom, blue 50%, transparent 50%);
}
<div class="triangle"></div>

But the diagonal doesn't look crisp. How could I do the same in CSS without using gradient?


回答1:


You can blur the edge a bit

.triangle {
    width: 100%;
    height: 120px;
    background: linear-gradient(to right bottom, blue 49.5%, transparent 50%);
}
<div class="triangle"></div>

the border approach as mention could be done this way to be similar :

.triangle {
  width:0;
  border-style:solid;
  border-width: 0px 0px 120px 100vw;
  border-color:transparent transparent transparent blue ;
}
<div class="triangle"></div>

Best is to use an SVG ....




回答2:


The trick is to make a triangle out of the border. Since CSS does not allow using percentage in border-width, I'm using 100vh instead of 100%.

Please try this:

.triangle {
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 0px 0px 120px 100vw;
    border-color:transparent transparent transparent blue ;
}



回答3:


Why dont you try without gradient property using border-width.I have implemented one using border-width which gives the boundaries more crisp. Here is the runable version.

.triangle {
    width: 100%;
    height: 120px;
    background: linear-gradient(to right bottom, blue 50%, transparent 50%);
}
.container{
  width : 300px;
}
.triangleUsingbordermethod {
    
    border-top-color: blue;
    border-top: 60px solid blue;
    border-left: 50% solid black;
    border-left: 150px solid blue;
    border-right: 150px transparent solid;
    border-bottom: 60px transparent solid;
}
<div class='container'>
 <div class="triangleUsingbordermethod"></div>
</div>


来源:https://stackoverflow.com/questions/42877961/a-triangle-in-css-that-takes-the-whole-width-with-a-fixed-height

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!