Responsive circle with centered content

29,146

Solution 1

Viewport Units

If you use the same viewport unit (either vw or vh) then you should get a responsive circle.

A viewport unit of 100 would be 100% of either the width or height. Therefore it is very similar to using a percentage.

div {
  width: 10vw;
  height: 10vw;
  border-radius: 50%;
  background: blue;
}
<div></div>

Solution 2

You can make a circle with centered content with:

  • padding-bottom to keep the aspect ratio of the circle according to it's width (more info here)
  • transform:translate(-50%,-50%); with absolute positioning to center the content verticaly and horizontaly in the circle (see approach 1 in this answer)

.circle{
  position:relative;
  width:50%;
  padding-bottom:50%;
  background:gold;
  border-radius:50%;
}
.circle h3{
  position:absolute;
  top:50%; left:50%;
  transform: translate(-50%, -50%);
  margin:0;
}
<div class="circle">
  <h3>Hello</h3>
</div>

Note that you will need to add vendor prefixes to the transform property to maximize browser support (see canIUse for more info).

Solution 3

CSS has the aspect-ratio property for this, which applies on width and height of the element.

More for web: https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio

More for react native: https://reactnative.dev/docs/layout-props#aspectratio

Share:
29,146
Admin
Author by

Admin

Updated on August 02, 2022

Comments

  • Admin
    Admin almost 2 years

    Is there a way to make the following:

    #id {
      border-radius: 100px;
      width: 100px;
      height: 100px;
    }
    <div id="circle">
      <h3>Hello</h3>
    </div>

    A round div with the text centered vertically and horizontally. At the same time keeping the circle responsive.
    By that I mean having a width of say 50% of the containing div, at the same time keeping the height percentage equal as to make a circle.

    And changing the static 100px to pertentages makes the circle oval.