In this article, we will review CSS gradients by creating different flags using a single HTML element for each of them. As part of the experience, we will also check the ::before and ::after pseudo-elements, and the clip-path property.
We will code simple flags and avoid coding the coats of arms as they would be tough in CSS. It wouldn't be impossible, but it's not a task worth doing either. Use SVG for that.
I used the Wikipedia page for the different flags to get dimensions, sizes, positions, and colors. My apologies in advance if they include any errors.
Let's start by adding what will be the HTML code of our flags, and some common styling:
<div> <pre class="brush:php;toolbar:false">.flag { display: inline-grid; height: 1em; vertical-align: top; position: relative; overflow: hidden; }
Here's a short explanation of what they do:
Some of these are over-engineering –yes, you can over-engineer CSS– because most flags will not need them. Especially the ones that we will code in this article… but eventually you'll find some that require the properties, and why not have them directly in the class, instead of having to add them individually several times?
A linear gradient creates a progressive color transition in a single direction (along a line, thus the name). By default, the direction is vertical from top to bottom, which makes creating flags simple.
Let's start with Poland's flag. It has two colors that occupy the same height: the top is white, and the bottom is red. This is one of the simplest gradients you'll find.
.flag.poland { background: linear-gradient(white 50%, red 50%); aspect-ratio: 8 / 5; }
This gradient sets white as the color from the top until it reaches 50% (half the flag), and then it changes to red, which starts at 50% too.
We also added an aspect-ratio: 8 / 5; because that is the official proportion for the flag of Poland (5:8). Feel free to ignore that property in the following examples, but remember to add it or the flag will not have a width and will be invisible!
CSS gradients are not limited to two colors, they can have as many as you want –but notice that some browsers may not display the gradient correctly if there are too many colors.
One example of this would be Germany's flag, where we'll have three colors from top to bottom:
<div> <pre class="brush:php;toolbar:false">.flag { display: inline-grid; height: 1em; vertical-align: top; position: relative; overflow: hidden; }
We made the notation of this example multiline and extra lengthy on purpose. Notice how we added two values after the value. They are the starting and end stops for each color respectively. In the example above, black will start from the top (0%) and go to one-third of the flag (33.33%), red will begin directly after (33.33%) and go to two-thirds of the flag (66.66%), and finally, yellow will start directly after 66.66% and go until the bottom of the flag (100%). In the case of a flag, the end and following start values will match, but if they don't, the browser will transition the colors progressively.
Considering that the first color will start at 0, and the last one will end at 100% by default, we can eliminate those values from the linear gradient. Also, any starting value lower than the previous end will cause a sharp stop between the colors. We want that for our flags and don't want to type too much, so we can just put the lowest value we can for the start value: 0% or just 0. That way, the CSS above would be reduced to something that yields a similar result, but that is considerably shorter:
.flag.poland { background: linear-gradient(white 50%, red 50%); aspect-ratio: 8 / 5; }
It would be boring –and useless– if we could only generate vertical linear gradients. There are ways to change the direction the gradient will be drawn. Let's check a couple of them:
Let's take Belgium's flag as an example. The colors are not stacked vertically but horizontally: black, yellow, and red respectively from left to right. We can achieve this in at least two different ways:
<div> <pre class="brush:php;toolbar:false">.flag { display: inline-grid; height: 1em; vertical-align: top; position: relative; overflow: hidden; }
A radial gradient creates a progressive color transition from one origin point out to all directions, generating a radial effect that looks like an ellipse of color (or a circle if the sides are equal). By default, that point is the element's absolute center –horizontally and vertically.
A couple of important things to take into account:
With these initial thoughts in mind (and keywords), let's create some flags!
The flag of Japan is a big red circle in the center of a white flag. This is one of the simplest radial gradients we can find, and we will get to use the circle keyword that we reviewed earlier, because the flag is rectangular, and if we don't use it, we'll get an ellipse instead.
.flag.poland { background: linear-gradient(white 50%, red 50%); aspect-ratio: 8 / 5; }
We combined the closest-side size keyword, with the circle shape keyword to generate a circle that is 60% of the height (as the top and bottom sides are closer than the left and right).
If we could only create circles and ellipses from the element's center, we could replicate some flags with CSS (e.g. Laos or Burundi). Still, we couldn't develop others with circles off-center (e.g. Costa Rica or Ethiopia).
The radial-gradient() method allows us to indicate the point of origin of the gradient. We do it by using at posX posY after the size and shape keywords (if any). Let's try to create Bangladesh's flag with it:
<div> <pre class="brush:php;toolbar:false">.flag { display: inline-grid; height: 1em; vertical-align: top; position: relative; overflow: hidden; }
What happens when we start moving the center of the gradient? The distance to the farthest corner changes! That will lead to trigonometric calculations to adjust the size accordingly… or instead, we could identify a different point of reference that isn't the farthest corner (like closest-side in this case).
To avoid this, we can specify an absolute size for width and height. If we do that, we won't be able to identify if it's a circle or an ellipse because those absolute values will determine the shape.
A conic gradient creates a progressive color transition from one origin point rotating around it clockwise. It may sound complex to visualize like that, so I prefer to use an example when I explain it to people: imagine a regular linear gradient printed on a paper (so far, so good); now you take the paper, fold over one side and roll it into a cone (thus the name!) The resulting figure will look like a conic gradient from above. I hope that was helpful.
As with the radial gradients, a conic gradient's default point of origin is the element's absolute center. Also as the radial gradients, we can change that point by using at posX posY.
This is a fairly simple flag to create with a conic gradient. First, we need to position the center at 40% horizontally and 50% vertically, then specify the stopping points.
.flag.poland { background: linear-gradient(white 50%, red 50%); aspect-ratio: 8 / 5; }
As I said, piece of cake! As there is not much to it, here's a fact you may not know about the flag of Benin: yellow represents the nation's treasures, red represents the courage of their ancestors, and green represents the hopes of democracy.
Based on that, let's see a way of drawing the flag of the Czech Republic:
.flag.germany { aspect-ratio: 5 / 3; background: linear-gradient( #000 0.00% 33.33%, #f00 33.33% 66.66%, #fc0 66.66% 100.00% ); }
This works just fine, but notice how we are using #fff two times. Wouldn't it be nice if we could use it only once? As you may have guessed, the answer is that we can! A gradient gradient doesn't necessarily need to start from the 0deg. We can specify a starting position using from [angle].
For example, let's say that we want to start from the red color:
<div> <pre class="brush:php;toolbar:false">.flag { display: inline-grid; height: 1em; vertical-align: top; position: relative; overflow: hidden; }
The angle can be a positive or negative value, then we'd be moving the starting point clockwise or counter-clockwise, respectively.
We have learned how to use linear, radial, and conic gradients to generate relatively simple flags… but sometimes flags can get complicated and a single gradient won't do. What can we do in that case?
CSS allows multiple background images (and gradients) in an element. We need to separate their values with a comma. As it may be counterintuitive, one important thing to remember is that the top backgrounds will overlap and hide the bottom ones.
The flag of Sweden is a yellow cross over a blue background. We can generate each yellow bar using a linear gradient transparent-yellow-transparent:
.flag.poland { background: linear-gradient(white 50%, red 50%); aspect-ratio: 8 / 5; }
This example has more than meets the eye:
While the previous flag showed multiple gradients in action, it was not great to showcase how they stack as it used transparencies. So, let's see another example –One that uses multiple gradients of different types.
.flag.germany { aspect-ratio: 5 / 3; background: linear-gradient( #000 0.00% 33.33%, #f00 33.33% 66.66%, #fc0 66.66% 100.00% ); }
When combining backgrounds, you are not limited to only one gradient type. You can use any kind.
So far, we've seen linear, radial, and conic gradients, and how they can be combined. But in all cases, the gradient occupied the whole flag. Some transparencies may not make it look that way, but the gradients' size was always 100% of the width and height.
But there are ways of changing the gradient's size to fit better our needs. The simplest one is to specify a background-size. If the size is smaller than the container, the background will repeat (unless we use something like background-repeat: none.)
Let's review an example with the flag of Qatar. The flag repeats a pattern nine times and can be easily replicated with a conic gradient. If we specify that the gradient's width should be 100% of the flag, and its height one-ninth of the flag's height, the browser will repeat the background until the container is filled, completing the drawing for us.
<div> <pre class="brush:php;toolbar:false">.flag { display: inline-grid; height: 1em; vertical-align: top; position: relative; overflow: hidden; }
Of course, once we specify a size, we can also specify the position where the gradient will be located. We would do that with background-position (and this is where the background-repeat property will come in handy).
.flag.poland { background: linear-gradient(white 50%, red 50%); aspect-ratio: 8 / 5; }
Notice that we don't need to specify a size and position for the last color. You can only set one that will automatically occupy the whole container.
We can separate the values of the background images, sizes, and positions with commas. That is convenient when there are only a few of them, but it can be a real pain in the neck if we have several backgrounds. It's easy to get lost and mix values.
Instead, we can use the short form of the background property to provide all values at once: background: gradient position / size repetition, like shown below:
.flag.germany { aspect-ratio: 5 / 3; background: linear-gradient( #000 0.00% 33.33%, #f00 33.33% 66.66%, #fc0 66.66% 100.00% ); }
We have seen linear, radial, and conic gradients, but each variation allows us to add "color patterns." Flags are perfect for this: many consist of repeating horizontal lines.
I am talking about the repeating- gradients. They behave the same as the regular gradients they repeat the specified pattern until it reaches 100% or 360 degrees. There are three repeating gradients:
Let's take the Greek flag as an example. We could have 3 or 4 big linear gradients to achieve it, or we can use three repeating linear gradients:
To achieve the cross at the top left, we must define both position and size for the first two linear gradients.
.flag.germany { aspect-ratio: 5 / 3; background: linear-gradient(#000 33.33%, #f00 0 66.66%, #fc0 0); }
Uganda's flag has a beautiful grey-crowned crane that we will not code in CSS for practical reasons. We will focus on the other two flag parts: a white circle at the center and several horizontal lines in black, yellow, and red.
This composition can be achieved in two different ways:
The first option would be like this:
<div> <pre class="brush:php;toolbar:false">.flag { display: inline-grid; height: 1em; vertical-align: top; position: relative; overflow: hidden; }
The second option would look like this:
.flag.poland { background: linear-gradient(white 50%, red 50%); aspect-ratio: 8 / 5; }
But both options end up looking the same. It is important to remember that in CSS, like in any other programming style, there is usually more than one way to achieve our goals.
The term "single-element flags" can be misleading. All non-empty HTML elements include –at least– two pseudo-elements that we can use to draw too: ::before and ::after. So we truly have three elements that can be styled separately and provide many possibilities:
If you coded Qatar's flag using gradients as described above, you might have noticed that the gradient's triangular edges look too sharp and ugly on some monitors. There are many ways to solve this, but a solution I like is using a pseudo-element with clip-path to make smoother and cleaner lines.
This option will simplify the code compared to using several linear gradients and the pixel difference trick explained in the following section.
.flag.germany { aspect-ratio: 5 / 3; background: linear-gradient( #000 0.00% 33.33%, #f00 33.33% 66.66%, #fc0 66.66% 100.00% ); }
The pseudo-elements in this case don't have to be limited to complex patterns. Take for example the flags of Cuba, Bahamas, or Jordan. They have triangles on the left side that we drew using conic gradients. Those gradients have an issue: the edges will look too hard or pixelated on certain monitors –there's a trick to solve this with linear gradients in the following section–. Instead, we could create the triangle with a pseudo-element (a three-point polygon path) and the edges will look smoother. Similar to the flag of Bahrain above.
I got the approximate points of the vertex points for a five-point star and applied them using clip-path in the ::before and ::after pseudo-elements. Many CSS artists will consider using clip-path cheating, and the star can be drawn with conic gradients. But for simplicity, I'll leave it as a clip-path.
Adding a conic gradient as the flag background, and the stars in the pseudo-elements, we can draw the flag of Panama in no time:
<div> <pre class="brush:php;toolbar:false">.flag { display: inline-grid; height: 1em; vertical-align: top; position: relative; overflow: hidden; }
Remember that when you combine backgrounds, they will stack in the order they are listed. That means, the first one will go on top and overlap the ones below, and subsequently.
While it makes sense from a designing perspective, it may be counterintuitive from a CSS point of view, where the cascade makes the last appearance of a property or class take precedence over the ones previously defined.
In the article, I mentioned how the gradient edges may look too sharp or pixelated. This happens because of how the browser renders the gradients –and it's annoying, especially because it doesn't happen for hard-stop edges on SVG.
For example, the line here may not look great on all monitors:
.flag.poland { background: linear-gradient(white 50%, red 50%); aspect-ratio: 8 / 5; }
A trick to avoid this is adding a pixel difference between the endpoint and the next beginning point. Either by subtracting or adding 0.5px respectively from each of them or, simpler, just subtracting/adding 1px from one of them. This line will look smooth on all the monitors:
.flag.germany { aspect-ratio: 5 / 3; background: linear-gradient( #000 0.00% 33.33%, #f00 33.33% 66.66%, #fc0 66.66% 100.00% ); }
A common mistake when working with repeating gradients is not adding a start point for the first color. This will cause the gradient to look funky. If your repeating gradients are not working as expected, always verify that you added a 0 (or whatever value) there!
Pseudo-elements can be intimidating at first, but they are no more different than any other element, they are just attached to the HTML element with them.
Don't forget to add the content property with a value (an empty string is common when you only want it to appear). Otherwise, the pseudo-elements will not be visible!
When drawing in CSS and creating CSS Art, many people will claim that using the clip-path property is cheating. It makes things easier and is a useful tool in your belt. I wouldn't discard it just because it's "cheating."
Learn how to use clip-path –and mask!– It will eventually come in handy in a project.
Now it's time for you to practice CSS gradients. Please give it a go and try to recreate some flags by yourself. Here's a list of countries with good flags to practice (sorted in order of complexity):
And remember: there's not a unique way of coding a flag. Each of them can be done in many different ways. Use the gradients you are more comfortable with or know will look best.
The above is the detailed content of Alvaro Montoro Presents: Fun with Flags… with CSS. For more information, please follow other related articles on the PHP Chinese website!