Search code examples
csscss-shapes

How to correctly set transform-origin to create a perfect X symbol?


I am trying to make a perfect "X" for close button (codepen). I think my concept or knowledge of transform-origin is limited. What am I doing wrong? Following is my code

.circle {
  width: 100px;
  height: 100px;
  background: black;
  border-radius: 50%;
  position: absolute;
}

span {
  display: block;
  width: 100%;
  height: 5px;
  background: white;
  border-radius: 20%;
  margin-top: 5px;
  position: absolute;
}

span:first-child {
  transform: rotate(45deg);
  transform-origin: center left;
  top: 0%;
  left: 20%;
}

span:last-child {
  transform: rotate(-45deg);
  transform-origin: bottom right;
}
<div class="circle">
  <span></span>
  <span></span>
</div>


Solution

  • No need transform-origin and extra element, you can simply do it with one element and a gradient for each line:

    .circle {
      width:50px;
      height:50px;
      border-radius:50%;
      background:
        /*horizontal line centred [width=100% and height=5px]*/
        linear-gradient(#fff,#fff) center/100% 5px,
        /*Vertical line centred [width=5px and height=100%]*/
        linear-gradient(#fff,#fff) center/5px 100%, 
        /*black background color*/
        #000;
      background-repeat:no-repeat;
      transform:rotate(45deg);
    }
    <div class="circle">
    </div>

    Here is a version with transparency:

    .circle {
      width:50px;
      height:50px;
      border-radius:50%;
      background:
        linear-gradient(#000,#000) top    left,
        linear-gradient(#000,#000) top    right,
        linear-gradient(#000,#000) bottom left,
        linear-gradient(#000,#000) bottom right;
      background-size:calc(50% - 3px) calc(50% - 3px);
      background-repeat:no-repeat;
      transform:rotate(45deg);
    }
    
    body {
      background:pink;
    }
    <div class="circle">
    </div>