问题
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.
回答1:
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/
回答2:
Reponsive triangles can be achieved with just CSS by taking advantage of padding being calculated against parent’s width to cover a big fixed-width triangle. To create an up-pointing triangle with 100% width:
.triangle-up {
width: 50%;
height: 0;
padding-left:50%;
padding-bottom: 50%;
overflow: hidden;
}
.triangle-up div {
width: 0;
height: 0;
margin-left:-500px;
border-left: 500px solid transparent;
border-right: 500px solid transparent;
border-bottom: 500px solid green;
}
Or using pseudoelements and just one div:
.triangle-up {
width: 50%;
height: 0;
padding-left:50%;
padding-bottom: 50%;
overflow: hidden;
}
.triangle-up:after {
content: "";
display: block;
width: 0;
height: 0;
margin-left:-500px;
border-left: 500px solid transparent;
border-right: 500px solid transparent;
border-bottom: 500px solid #959595;
}
Here's a fiddle. For the full explanation on how these work and the down, left and right pointing triangle snippets see my article on Pure CSS responsive triangles. The CSS given is for a triangle with base-height ratio of 2. Trying to change the triangle's proportions without knowing how these triangles fake responsiveness may be complicated.
回答3:
You could achieve the same using simple CSS
To make it responsive use it in media queries..
Try the following JsFiddle
http://jsfiddle.net/arunberti/52grj/
.triangle {
width: 0;
height: 0;
border-top: 50px solid rgba(255%, 204%, 0%, 1);
border-right: 100px solid transparent;
}
来源:https://stackoverflow.com/questions/17826057/creating-responsive-triangles-with-css