Search code examples
cssradial-gradients

Pure CSS - Using mask-image and radial-gradient to make diamond like form


I am trying to make some diamond form in pure CSS, trying to use mask-image and radial-gradient but I don't quite succeed.

The 2 form I like to do are :

Diamond empty

Diamond filled

I tried something to alter a block of color black like

width: 20px;
height: 20px;
background: #000;
-webkit-mask-image: radial-gradient(circle 7px at top, transparent 7px, black 50%);

I don't know how to solve my problem and even it is doable through only pure CSS :)


Solution

  • you don't really need mask here. Multiple radial-gradient() can do it

    .box {
      width:50px;
      height:50px;
      margin:10px;
      --c:transparent 90%,#000 92% 98%,transparent; /* adjust this */
      background:
        radial-gradient(farthest-side at top   left  ,var(--c)) top left,
        radial-gradient(farthest-side at top   right ,var(--c)) top right,
        radial-gradient(farthest-side at bottom left ,var(--c)) bottom left,
        radial-gradient(farthest-side at bottom right,var(--c)) bottom right;
      background-size:51% 51%; /* add this (each layer take half the height and width) */
      background-repeat:no-repeat;
    } 
    
    .alt {
      --c:transparent 90%,#000 92%; /* we simply remove the last transparent for the full shape */
    }
    
    body {
      background:pink;
    }
    <div class="box"></div>
    
    <div class="box alt"></div>

    Mask can be useful in case you want a fancy background:

    .box {
      width:50px;
      height:50px;
      margin:10px;
      background:linear-gradient(45deg,red,blue);
      --c:transparent 90%,#000 92% 98%,transparent; /* adjust this */
      -webkit-mask:
        radial-gradient(farthest-side at top   left  ,var(--c)) top left,
        radial-gradient(farthest-side at top   right ,var(--c)) top right,
        radial-gradient(farthest-side at bottom left ,var(--c)) bottom left,
        radial-gradient(farthest-side at bottom right,var(--c)) bottom right;
      -webkit-mask-size:51% 51%; /* add this (each layer take half the height and width) */
      -webkit-mask-repeat:no-repeat;
    } 
    
    .alt {
      --c:transparent 90%,#000 92%; /* we simply remove the last transparent for the full shape */
    }
    
    body {
      background:pink;
    }
    <div class="box"></div>
    
    <div class="box alt"></div>