Adding Transform CSS property to div modifies its border-radius

Viewed 63

I have 2 div elements: a parent and its child, and need to have rounded corners on both of them. Setting border-radius to for example 20px usually does that, but once I add transform property to child specifically scaleX, border-radius becomes smaller and visually doesn't change even if I set its value to higher, here is the sample code:

.container {
  background-color: grey;
  height: 20px;
  overflow: hidden;
  border-radius: 20px;
}

.item {
  background-color: red;
  transform-origin: 0 50%;
  transform: scaleX(0.5);
  border-radius: 20px;
  height: inherit;
}
<div class="container">
  <div class="item"></div>
</div>

and here's the codesandbox link of the following code: https://codesandbox.io/s/silent-worker-nt7i0v?file=/src/styles.css

and the image of the behavior: Note how border radius of the child looks different than that of the parent, even though they have the same value set for it.

enter image description here

4 Answers

You can definitely use width here, and you can definitely animate it too. Here's a quick example:

.container {
  background-color: grey;
  height: 20px;
  overflow: hidden;
  border-radius: 20px;
}

.item {
  background-color: red;
  width: 0%;
  border-radius: 20px;
  height: inherit;
  animation: fill 5s infinite;
}

@keyframes fill {
  from {
    width: 0%;
  }
  to {
    width: 100%;
  }
}
<div class="container">
  <div class="item"></div>
</div>

I believe the transform X is "squishing" the .item, and that's what you're seeing here. As an alternative, can you use width: 50% instead of transform: scaleX(0.5)? That will maintain the proper radius on .item

scaleX is squishing the .item div, if you would like to use transform especially you can fix like that but using animation or width could be better.

.item {
  background-color: red;
  transform: translateX(-50%);
  border-radius: 20px;
  height:inherit;
}

I think your code so complicated.

You can use simply width instead transform, transform-origin.

Just set simply like this.

.item {
  background-color: red;
  width: 50%;
  border-radius: 20px;
  height: inherit;
}
Related