CSS circle without using fixed width and height
This is so hacky, but it seems to check out on all the major browsers' latest versions, so I'll post it anyway. The basic principle is that percent-based padding (even top and bottom padding) are relative to the width of the parent. Setting it to 100%
with a width and height of 0
would theoretically mean that the height of the element would always be equal to the width. Combine that with a pseudo element and you don't even need to change the markup. I used flexbox to correct the centering of the content. It seems to work on the browsers I tested it on, but this is definitely dependent on recent versions because it uses flexbox
and display:table
. I also had to add a min-width
to ensure it doesn't appear out of shape for too little of content.
.circle {
background-color: red;
color: white;
text-align: center;
position: relative;
border-radius: 50%;
min-width: 1.25em;
display: inline-flex;
align-items: center;
justify-content: center;
}
.circle:after {
content: '';
padding-top: 100%;
display:table;
}
<div class="circle">5</div>
<br>
<div class="circle">102</div>
<br>
<div class="circle">4298347918</div>
Simple CSS for circles that works almost ever:
.circle {
position: relative;
border-radius: 50%;
width: 100%;
height: auto;
padding-top: 100%;
}
The trick is that the padding top is calculated on the width so you can use it for makinh height equals width
See this CSS only solution. Set the same value of min-width
and min-height
for 1 digit number. Use a pseudo element for vertical alignment and to maintain the square shape. With border-radius
applies to the container for the circle.
.circle {
display: inline-block;
border-radius: 50%;
min-width: 20px;
min-height: 20px;
padding: 5px;
background: red;
color: white;
text-align: center;
line-height: 1;
box-sizing: content-box;
white-space: nowrap;
}
.circle:before {
content: "";
display: inline-block;
vertical-align: middle;
padding-top: 100%;
height: 0;
}
.circle span {
display: inline-block;
vertical-align: middle;
}
<div class="circle"><span>8</span></div>
<div class="circle"><span>64</span></div>
<div class="circle"><span>512</span></div>
<div class="circle"><span>4096</span></div>