Search code examples
javascriptcsscss-transforms

Is it possible to skew HTML element by a number of pixels using CSS transform?


My problem is: there's a block containing variable number of HTML elements. Something like this...

<ul class="list">
  <li class="item">...</li>
  <li class="item">...</li>
  <li class="item">...</li>
</ul>

This block must have a skew on the right side (the content must not be skewed). The horizontal size of this skew must be fixed. So adding CSS rules like...

.list {
  position: relative;
  background: #A0A0FF;
}
.list:after {
  content: " ";
  display: block;
  position: absolute;
  top: 0;
  bottom: 0;
  right: -10px;
  width: 20px;
  transform: skewX(-15deg);
  background: #A0A0FF;
}

...won't do because in this case the skew will have variable horizontal size depending on the number of items in the list. The only solution that comes to my mind is to calculate the number of degrees in js. But this is kinda meh.
So my question is: is it possible to somehow skew an element by a number of pixels instead of degrees/radians using CSS?


Solution

  • You can achieve the same skew appearance by using a linear gradient on a pseudo-element.

    *,
    ::after,
    ::before {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    ul {
      width: 200px;
      background: #663399;
      margin: 25px auto;
      list-style-type: none;
      position: relative;
    }
    ul::after {
      position: absolute;
      content: "";
      top: 0;
      left: 100%;
      background: linear-gradient(to bottom right, #663399 0%, #663399 50%, transparent 50%, transparent 100%);
      width: 16px;
      height: 100%;
    }
    <ul class="list">
      <li class="item">...</li>
      <li class="item">...</li>
      <li class="item">...</li>
    </ul>
    
    <ul class="list">
      <li class="item">...</li>
      <li class="item">...</li>
      <li class="item">...</li>
      <li class="item">...</li>
      <li class="item">...</li>
      <li class="item">...</li>
    </ul>