Search code examples
htmlcssdiagonal

CSS diagonal div background


For a website I'm developing I need to include some diagonal shaped borders to a div. These are the main examples which I need to recreate.

double diagonal top border, triangle shaped

Now been scouting the web on how to achieve this, and my first thought as well would be by using ::before. However I can't get it to work without it being positioned absolute which messes up the entire page.

This is my code I have tried to achieve something like this:

.slider-container{
  background-color: $blue;
  width: 100%;
  overflow: hidden;
  position: relative;
  .col-md-3{
    img{
      padding: 40px;
      width: 100%;
      max-width: 400px;
      margin: auto;
    }
  }
  &::before {
    background: red;
    bottom: 100%;
    content: '';
    display: block;
    height: 100%;
    position: absolute;
    right: 0;
    transform-origin: 100% 100%;
    transform: rotate(-15deg);
    width: 150%;
  }
}
<section id="slider">
    <div class="container-fluid">
        <div class="row slider-container">
            <div class="col-md-3">
                <p>imgae 1</p>
            </div>
            <div class="col-md-3">
                <p>imgae 2</p>
            </div>
            <div class="col-md-3">
                <p>imgae 3</p>
            </div>
            <div class="col-md-3">
                <p>imgae 4</p>
            </div>
        </div>
    </div>
</section>

Note: it won't work in here but this is the result I get result


Solution

  • With just css and a bit tweaking based on your divs size you could create something like this:

    .myclass {
    width: 100px;
    height: 100px;
    background: linear-gradient(45deg, black 0%, black 26%, transparent 26%), linear-gradient(-45deg, black 0%, black 27%, transparent 27%)
    }
    
    .myclass2 {
    width: 100px;
    height: 100px;
    background: linear-gradient(-45deg, blue 0%, blue 27%, transparent 27%), linear-gradient(45deg, blue 0%, blue 26%, red 26%)
    }
    With transparency:
    <div class="myclass">My content here</div>
    <br/>
    Not as easy with transparent:
    <div class="myclass2">My content here</div>

    Edit: Just tested this in chrome, you might need special linear-gradients for older/other browsers.