Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Responsive CSS triangle with percents width

The code below will create an arrow right below an <a> element:

JSFiddle

.btn {      position: relative;      display: inline-block;      width: 100px;      height: 50px;      text-align: center;      color: white;      background: gray;      line-height: 50px;      text-decoration: none;  }  .btn:after {      content: "";      position: absolute;      bottom: -10px;      left: 0;      width: 0;      height: 0;      border-width: 10px 50px 0 50px;      border-style: solid;      border-color: gray transparent transparent transparent;     }
<a href="#" class="btn">Hello!</a>

The problem is that we have to indicate the link width to get an arrow of a proper size because we cannot indicate the border width in pixels.

How to make a responsive triangle percent based?

like image 420
sdvnksv Avatar asked Aug 18 '14 09:08

sdvnksv


2 Answers

You could use a skewed and rotated pseudo element to create a responsive triangle under the link :

DEMO (resize the result window to see how it reacts)

The triangle maintains it's aspect ratio with the padding-bottom property.

If you want the shape to adapt it's size according to it's content, you can remove the width on the .btn class

.btn {    position: relative;    display: inline-block;    height: 50px; width: 50%;    text-align: center;    color: white;    background: gray;    line-height: 50px;    text-decoration: none;    padding-bottom: 15%;    background-clip: content-box;    overflow: hidden;  }  .btn:after {    content: "";    position: absolute;    top:50px;  left: 0;    background-color: inherit;    padding-bottom: 50%;    width: 57.7%;    z-index: -1;    transform-origin: 0 0;    transform: rotate(-30deg) skewX(30deg);  }  /** FOR THE DEMO **/    body {    background: url('http://i.imgur.com/qi5FGET.jpg');    background-size: cover;  }
<a href="#" class="btn">Hello!</a>

For more info on responsive triangles and how to make them, you can have a look at Triangles with transform rotate (simple and fancy responsive triangles)

like image 193
web-tiki Avatar answered Sep 27 '22 19:09

web-tiki


Another solution to this would be to use a CSS clip-path to clip a triangle out of a coloured block. No IE support however, but could be used for internal tools etc.

DEMO

Written with SCSS for ease.

.outer {   background: orange;   width: 25%;   position: absolute;   top: 50%;   left: 50%;   transform: translate(-50%, -50%);   padding: 1em;    p {     margin: 0;     text-align: center;     color: #fff;   }    &:after {     content: '';     position: absolute;     top: 100%;     left: 0;      right: 0;     padding-bottom: 10%;     background: orange;     -webkit-clip-path: polygon(0% 0%, 100% 0%, 50% 100%);     clip-path: polygon(0% 0%, 100% 0%, 50% 100%);   }  } 
like image 45
Probocop Avatar answered Sep 27 '22 19:09

Probocop