Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

jquery - Creating responsive triangles with CSS

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

<div class="triangle"></div>

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...