Search code examples
csscss-shapes

How to make half-square background in css


square cut in half diagonaly

Is it possible to make in pure css background for half square like on the image. I know that it can be done with an image as background, but I need to use 5 different colours, and maybe in future the colours can be changed.


Solution

  • If your divs have fixed sizes, you can use borders to make two triangles as described in How do CSS triangles work?:

    div{
      display:inline-block;
      border-top:100px solid red;
      border-right:100px solid grey;
      }
    <div></div>

    To make other sizes, colors, you need to tweak the border properties :

    div {
      display: inline-block;
    }
    div:nth-child(1) {
      border-right: 100px solid red;
      border-top: 100px solid grey;
    }
    div:nth-child(2) {
      border-left: 100px solid red;
      border-top: 100px solid grey;
    }
    div:nth-child(3) {
      border-right: 50px solid red;
      border-top: 100px solid grey;
    }
    div:nth-child(4) {
      border-right: 100px solid red;
      border-bottom: 50px solid grey;
    }
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>