Creating responsive triangles with CSS

前端 未结 3 578
一个人的身影
一个人的身影 2020-12-15 00:12

I was trying to create triangles in CSS for a responsive site today and couldn\'t find a good example on stackoverflow, so here\'s how I did it.

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-15 00:35

    Making angular shapes responsive is a little tricky because you can't use percentages as border values in your CSS, so I wrote a couple functions to calculate the page width and resize a triangle accordingly. The first calculates the size on loading the page, the second recalculates the size as the page width changes.

    CSS:

    .triangle {
        width: 0;
        height: 0;
        border-top: 50px solid rgba(255, 255, 0, 1);
        border-right: 100px solid transparent;
    }
    

    HTML:

    JS:

    $(document).ready(function () {
        var windowWidth = $(window).width();
        $(".triangle").css({
            "border-top": windowWidth / 2 + 'px solid rgba(255, 255, 0, 1)'
        });
        $(".triangle").css({
            "border-right": windowWidth / 1.5 + 'px solid transparent'
        });
    });
    
    $(window).resize(function () {
        var windowWidthR = $(window).width();
        $(".triangle").css({
            "border-top": windowWidthR / 2 + 'px solid rgba(255, 255, 0, 1)'
        });
        $(".triangle").css({
            "border-right": windowWidthR / 1.5 + 'px solid transparent'
        });
    });
    

    Here's a jsFiddle - http://jsfiddle.net/craigcannon/58dVS/17/

提交回复
热议问题