css set border-radius relative to height

Viewed 2723

As i understand it, in CSS the border-radius property defines how far down a side a rounded corner should start. The distance can be in relative units, such as %. However, when set in percent CSS of course take % of width on the x-axis and % of height on y. I want the element to be a bar with rounded ends:

div {
    margin: 50px auto;
    border: 1px solid black;
    width: 800px;
    height: 150px;
    border-radius: 75px; /* hardcoded, but would like it to be 50% of height */
}

Pair this with an standard html doc with just a single empty div in the body. In the actual case i need this for, the height of the div is also a percentage, so i cannot just calculate it manually. How can i set the border radius to 50% of height on both axes? I couldn't seem to find this neither asked or done anywhere, so maybe there is a really obvious way of doing this that i'm just missing?

3 Answers

You can also use:

border-radius: 50vh;   

Seems like when provided higher value of radius working for different width and height values.

div {
  margin: 50px auto;
  border: 1px solid black;
  width: 400px;
  height: 150px;
  /* hardcoded, but would like it to be 50% of width */
  border-radius: 50vh;
}
<div>

</div>

It's a bit of a cheat, but you can just set the border-radius to something huge and it will end up looking the same regardless of the size:

div {
    border-radius: 500px;
}

This can be done using css variables or pre-processor variables(like in sass, less...), if you don't want to hardcode it

div {
    --height: 150px; /* can be percentage too */
    margin: 50px auto;
    border: 1px solid black;
    width: 800px;
    height: var(--height);
    border-radius: calc(var(--height) * 0.5); /* 50% of height */
}

I don't think Manjuboyz's answer's your question. The main question was setting border-radius as 50% of the container's height, not the viewport's.

vh converts to the viewport's height, not the container's height.

Look at these: css tricks - Fun with viewport units, mdn docs for vh

Related