How to make a diagonal border fit the corners

1000 views Asked by At

based on this question

How to add a gradient border above image (diagonal border)

I want to make the same but on an small div, but the diagonal line doesn't fit the borders

Here is the fiddle

http://jsfiddle.net/wo8gbhx3/36/

HTML

<div class="testing">
    <ul>
        <li class="selected unavailable">
            <a href="#">
                <img src="http://placehold.it/25x25"/>
            </a>
        </li>
    </ul>
</div>

And the CSS

.testing ul {
  list-style: none;
}
.testing ul li {
  width: 20px;
  height: 18px;
}
.testing ul li img {
  width: 100%;
  height: 100%;
  display: block;
}
.unavailable {
  position: relative;
}
.unavailable a:after {
  content: '';
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  position: absolute;
  background: repeating-linear-gradient(135deg, transparent, transparent 16px, #000 18px);
  z-index: 2;
}
3

There are 3 answers

2
Jeff Clarke On

Adjust the spacing in the background property of the .unavailable a:after rule:

background: repeating-linear-gradient(135deg, transparent, transparent 12px, #000 13px);

Also, since the you have specified a 135 degree angle, this works best on a square. So I've adjusted the width and height of the div to be equal:

.testing ul li {
  width: 18px;
  height: 18px;
}

Alternatively you can play with the angle to get it corner to corner for a rectangle, but the line may look rough.

Example: http://jsfiddle.net/wo8gbhx3/39/

0
crazymatt On

It seems since your diagonal line is not position exactly in the bottom left corner so you just need to skew your .unavailable a:after to make it fit from corner to corner. To do this just adjust the width/height properties like this and setting the right:0 instead of left.

.unavailable a:after {
  content: '';
  width: 25px;
  height: 18px;
  top: 0px;
  right: 0px;
  position: absolute;
  background: repeating-linear-gradient(135deg, transparent, transparent 16px, #000 18px);
  z-index: 2;
}

You can see your updated Fiddle here. Just so you know its going to appear a little off because your box is not even height and width (you're using 20 by 18)

2
vals On

In modern browsers , you can get it to auto-adjust.

The angle can be get automatically setting it to a corner.

And the position can be get using calc

background: linear-gradient(to top left, 
    transparent calc(50% - 1px), 
    black calc(50% - 1px), 
    black calc(50% + 1px), 
    transparent calc(50% + 1px));

fiddle