Search code examples
cssresponsive-designcss-shapesshapes

Responsive slanted border


I have created a slant style triangle using borders to use on navigation items, however the border that is used to define the length of the slant is fixed and it needs to adapt based on the content inside the list item. I also want to use the same css class for each list item.

Is this the best solution for what I am trying to achieve or is there an alternative method that has the same result?

I am open to JS solutions too.

I have used the following CSS so far:

li {
    float: left;
    position: relative;
    height: 20px;
    background: #a1a8ad;
    padding: 5px 12px;
    margin-right: 10px;
    list-style: none;
}

li:before {
    content: "";
    position: absolute;
    top: -3px;
    width: 0;
    height: 1px;
    left: 0px;
    border-right: 63px solid #a1a8ad; /* razorblade color */
    border-top: 2px solid rgba(0, 0, 0, 0); /* transparent */
}

JSFiddle here


Solution

  • You can't use percentages for the border-width but you can use a rotated pseudo element to make the slanted top border :

    li {
      float: left;
      position: relative;
      margin-right: 10px;
      list-style: none;
      overflow: hidden;
      padding-top: 8px;
    }
    li a {
      display: block;
      background: #a1a8ad;
      padding: 5px 12px;
      color: #000;
      height: 20px;
      text-decoration: none;
    }
    li:before {
      content: "";
      position: absolute;
      top: 0;
      right: 0;
      width: 150%;
      height: 30px;
      background: #a1a8ad; /* razorblade color */
      -webkit-transform-origin: 100% 0;
      -ms-transform-origin: 100% 0;
      transform-origin: 100% 0;
      -webkit-transform: rotate(-2deg);
      -ms-transform: rotate(-2deg);
      transform: rotate(-2deg);
      z-index: -1;
    }
    <nav>
      <ul>
        <li><a href="#">Home</a>
        </li>
        <li><a href="#">About Us</a>
        </li>
      </ul>
    </nav>