Explain Codes LogoExplain Codes Logo

Draw circle using CSS alone

html
responsive-design
css
web-development
Anton ShumikhinbyAnton Shumikhin·Sep 20, 2024
TLDR

Make a flawless circle by setting the width and height of a div as equals and applying border-radius: 50%. Include a background to make it visible:

.circle { width: 50px; /* as round as a well-fed hamster */ height: 50px; /* saw a pizza this big once */ border-radius: 50%; /* shaved off the crust corners to make it circular */ background: red; /* juicy-red like a tomato */ }

Indent this into your HTML:

<div class="circle"></div>

This forms a 50px red circle. Tweak width, height, and background to alter.

Progressing with CSS

CSS offers a plethora of tools to embellish the way your circle shows up on the screen. Let's explore them:

Your circle's halo – box-shadow

You can make a simple circle more tangible with box-shadow:

.circle { /* ...previous properties... */ box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); /* like the circle just discovered a ring of shadow */ }

Decorate with pseudo-elements

Pseudo-elements like :before or :after can give your circle complex shapes or layers:

.circle:before { content: ''; /* ...more properties... */ border-radius: 50%; /* all TF back to being round again */ z-index: 1; /* stays on top like the cream of the crop*/ }

Responsive dimensions

Use adjustable units like em, vw, or % instead of fixed pixel amounts to warrant your circle's proper scaling:

.circle { width: 10vw; // circle stays true size whether on a phone or Godzilla's TV height: 10vw; /* ...other properties... */ }

Ensuring cross-browser compatibility

Accessible design means your CSS circles should show up on any browser:

Catering for older browsers

Safeguard older versions of Firefox and Safari by including -moz- and -webkit- prefixes:

.circle { -webkit-border-radius: 50%; /* getting the browsers back into the circle of trust */ -moz-border-radius: 50%; border-radius: 50%; }

Plan B for ancient IE

IE8 and below can only fancy a circle using a :before pseudo-element with Unicode character (●):

.circle:before { content: "\25CF"; /* gourmet Unicode jellybeans, yum! */ font-size: 50px; line-height: 50px; }

Backing up with HTML character codes

The HTML character code &#8226;, used as a last resort, can conjure a circle in a minimal-CSS environment:

<span>&#8226;</span>

You can style this character with font-size and color to convert it into a primitive circle.