Home > Back-end >  Why does border-top not create linear end with border-radius applied to it?
Why does border-top not create linear end with border-radius applied to it?

Time:10-07

I wanted to create a simple loading animation with CSS, so I needed a border which was only visible 1/4 around the element. The element also needed to be round. I stumbled upon border-top and created the following CSS, which is applied to the "loading element":

.loading {
  width: 5rem;
  height: 5rem;
  border-radius: 50%;
  border-top: 5px solid red
}
<div class="loading"></div>

However, now I've gotten a problem, the border created with border-top surrounds approximately 1/2 of the element and has gotten a weirdly shape.

Image of the created border

I've, searched for a solution and found out, that I also need to add a border around the complete element, to make it look, like I want it to look. So, I've added the following CSS: border: 5px solid transparent and achieved the result I wanted. The border takes up 1/4 of the element and has gotten linear ends:

Image of the achieved result

Why does my solution work, why does my first attempt surround the element by a half and why is my first attempt so oddly shaped?

CodePudding user response:

CSS borders meet at an angle, so the shape of their ends is determined by the width of each border. This is how borders are used to create CSS triangles. This article has a good overview of how it works, with a nice visual example near the start: The secret of CSS triangles

Of course, it's easier to see what's going on when the borders are all the same width, and there is no border radius to complicate things. But when you just have a single border with width, and border radius, then you've seen how that affects the meeting point.

I recommend you try creating a square div with 4 different coloured borders, and then experiment with each of their widths, and with border radius, using your browser's developer tools so you can see how the meeting points change.

CodePudding user response:

This is because the border width transitions to what it is on the adjacent sides (zero). Here I demonstrate with a wider border on the side.

.loading {
  width: 5rem;
  height: 5rem;
  border-radius: 50%;
  border-top: 5px solid red;
  border-right: 25px solid;
}
<div class="loading"></div>

You'd normally create this sort of effect using pseudo-elements or canvas.

CodePudding user response:

.loading {
  width: 5rem;
  height: 5rem;
  border-radius: 50%;
  border: 5px solid;
  border-color: #ef7d00 #d8d9d9 #d8d9d9 #d8d9d9;
}
<div class="loading"></div>

  • Related