CSS Moon Shape

by|inArticles||2 min read
Moon Phases<br>
Moon Phases<br>

CSS is awesome. It really is. Sometimes we can replace whole image/icon elements in a web project by simple CSS constructs. One of these constructs is the moon phase icon that I will explain in this article.

The basic idea is not very complicated. Since the moon is round (or let's say more or less round) we can already use basic CSS shapes. We can start off by a simple circle, like this:

.moon {
  border-radius: 50%;
  border: 1px solid red;
  width: 50px;
  height: 50px;
  background-color:lightgrey;
}

The 50% border-radius is a common technique to create circles. Nothing fancy here. As well, we give the whole circle a red border and a height/width of 50 px to have a better idea of what we are doing. The result should look something like this:

In terms of HTML elements, we will stop here. We really don't need more. We will use the two pseudo elements ::before and ::after to create the rest.

We can now proceed and style our ::before shape, which will be as well round and sit exactly inside our moon element. Hence, we will make our moon element relative in terms of positioning and give it a full height. Furthermore let's limit its width to 50% and color it yellow, so we can see the effect.

.moon {
  /* the code before */
  position: relative;
}

.moon::before {
  border-radius: 50%;
  height: 100%;
  width: 50%;
  background-color: yellow;
}

We should now see a lightgrey circle with a red border. The inner is to 50% filled with a yellow half-circle shape.

Great! What now? With the ::after element we can now create an ellipsis shape and place it in the middle of our circle:

.moon::after {
  position: absolute;
  content: ' ';
  border-radius: 50%;
  height: 50px;
  width: 30px;
  left: 10px;
  background-color: #48abe0;
}

I gave the ellipsis a blue color so we can see the effect and the position of or ellipsis. In general this completes our basic setup. From here we just need to adapt the colors to the desired moon shape. For instance, let's remove the red border and color the before and after pseudo elements in black:

Or, let's remove the ellipsis:

Ah, a perfect half moon. What if we color the ellipsis in lightgrey?

Awesome! All other moon variants can be derived from the seen examples. You can rotate the moon or as well flip the before element to be shown the other side. Once yo have the basic set-up and you understood the positioning of the elements, it should be easy to adapt to your use case. Just to give you an example. I have implemented this in the following tool (a moon calendar for fishing): Mondkalender für Angler

Thank you for reading this far! Let’s connect. You can @ me on X (@debilofant) with comments, or feel free to follow. Please like/share this article so that it reaches others as well.

Related Articles

© Copyright 2024 - ersocon.net - All rights reservedVer. 414