Responsive triangle div

若如初见. 提交于 2019-12-10 17:33:31

问题


I'm trying to create a responsive triangle div which will sit at the top of the page as a header.

I was able to achieve that with the following code:

div{
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 200px 400px 0 0;
  border-color: #007bff transparent transparent transparent;
}
<div></div>

The problem is that I want this triangle to be responsive to the width of the page and change proportionally in height as well.

I tried setting width and height to percent based, however that produced a really small triangle which you can see here:

http://jsfiddle.net/Ltbzkq0e/1/

How to make the borders work with percent without having to use webkits? Is that possible, if not how do I achieve this effect with webkits?

EDIT:

I would also like to fit content in this div. At the moment the only way I can think of is to use absolute positioning and set height to -20px, etc... Is there a better way of accomplishing this?


回答1:


You can use transform-rotate and a pseudo element to create a responsive triangle. This technique is detailed here : CSS triangles with transform rotate.

For your specific case it could look like this :

DEMO

.tr{
    padding-bottom:30%;
    position:relative;
    overflow:hidden;
}
.tr:before{
    content:'';
    position:absolute;
    top:0; left:0;
    width:120%; height:100%;
    background-color : #0079C6;
    
    -webkit-transform-origin:0 100%;
    -ms-transform-origin:0 100%;
    transform-origin:0 100%;
    
    -webkit-transform: rotate(-17deg);
    -ms-transform: rotate(-17deg);
    transform: rotate(-17deg);
}
.content{
    position:absolute;
}
<div class="tr">
    <div class="content"> ... CONTENT HERE ...</div>
</div>

If you need IE8 support, you will need to use a JS fallback. This answer describes a way to achieve it.




回答2:


if you don't care about IE8 and recent Android support — and since you need to have border-width proportional to the page size — you can use viewport-based (vw and vh) units

e.g.

border-width: 100vw 100vh 0 0;

example fiddle: http://jsfiddle.net/swbfqemr/



来源:https://stackoverflow.com/questions/26891619/responsive-triangle-div

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