How to make a CSS triangle background on a div without using border and image?

use*_*839 20 css

I know how to create triangles with CSS with borders and using images, but in my case, I'd like to use background color.

I want something like this image.

Can anyone help me?

Lor*_*nzo 27

另一种方法是使用背景线性渐变.诀窍是将方向设置为右下角,将第一个范围设置为白色(或透明),将第二个范围设置为要三角形的颜色.

在以下示例中,背景的前半部分是白色(从0%到50%),后半部分(从50%到100%)是浅灰色.

.triangle {
    width: 200px;
    height: 200px;
    background: linear-gradient(to bottom right, #fff 0%, #fff 50%, #a48d01 50%, #a48d01 100%);
}
Run Code Online (Sandbox Code Playgroud)

请注意,此属性仅受现代浏览器支持(IE 11 +,FF 49+)


SW4*_*SW4 16

The problem with creating triangles using CSS borders is their inflexibility when it comes to styling. As such, you can use a relatively fully pseudo fledged element instead, providing many more styling options:

Sure, you can do, e.g.:

Demo Fiddle

div{
    height:50px;
    width:50px;
    position:relative;
    overflow:hidden;
}
div:after{
    height:100%;
    width:100%;
    position:relative;
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    transform: rotate(45deg);
    content:'';
    display:block;
    position:absolute;
    left:-75%;
    background-image:url(http://www.online-image-editor.com/styles/2013/images/example_image.png);
    background-size:cover;
}
Run Code Online (Sandbox Code Playgroud)

  • ...只需设置背景颜色......? (3认同)

Jai*_*oya 6

试试这个工具来生成你想要的形状:https : //bennettfeely.com/clippy/。然后根据您的需要调整代码。例如,这是获得三角形的方法:

-webkit-clip-path: 多边形(50% 0%, 0% 100%, 100% 100%); 剪辑路径:多边形(50%0%,0%100%,100%100%);

但是,Support并不是最好的,因为它仅在 Firefox 中得到完全支持,在 Edge/IE 中不存在,因此不鼓励在生产网站上使用剪辑路径支持