Create a Single Div Star with CSS in Five Steps

You may or may not know that you can create a single div star in CSS pretty easily. But if you haven’t examined the code in depth, you may be curious to know what’s going on under the hood. This article shows you how to build a single div star in five basic steps. Once you have these five steps down, you can make a huge array of other CSS single div shapes.

Step 1: Create three shapes from one div, using the :before and :after pseudo-elements:

The single div star starts with CSS’s :before and :after pseudo-elements. If you don’t already know, :before and :after are a handy way to add dynamic content to an element without additional markup. Take a look at the following code:

See the Pen ERGPNr by Float Nine (@floatnine) on CodePen.

Clicking between the HTML, CSS, and Result tabs, you can see that we were able to give each part of our div (:before, :after, and square) its own background color and dimensions. Also, the :before and :after pseudo-elements have been positioned absolutely, relative to the main element (see more about this effect in my article, Absolute Relative Positioning). The next step is to transform these shapes into the pieces of our single div star.

Step 2: Turn the pieces of the element into triangles

The key to creating triangles (or any angular shape) in CSS is using the border property. Take a look at the following shape’s multicolored border:

See the Pen Step 2a by Float Nine (@floatnine) on CodePen.

See how I’ve given each side of the border its own color? That way you can see that they meet each other at 45 degree angles at the bottom two corners of the square. If we then reduce the width and height of the square to zero, we have nothing but borders left, meeting together at the top center:

See the Pen Step 2b by Float Nine (@floatnine) on CodePen.

 

I’ve increased the size of each border to 150px so you can see the triangles that emerge more clearly. The final step to creating a triangle is to set the background color of all but one of the border sides to transparent:

See the Pen Step 2c by Float Nine (@floatnine) on CodePen.

Be sure to remove the background color of the element as well, or it will show through. So now we have a triangle. That’s great! The next step to creating our single div star is to combine steps 1 and 2.

 

Step 3: Create three triangles using steps 1 and 2

By using our pseudo-elements in conjunction with the border triangle trick, it’s not too hard to create three triangles from one div:

See the Pen Step 3 by Float Nine (@floatnine) on CodePen.

Notice we have one smaller acute triangle, and two larger obtuse triangles. This was achieved by altering the size of the left, bottom, and right borders for each triangle to create the specific shapes. The bottom border of the acute triangle is much taller than it’s two side borders, while the obtuse triangles’ bottom borders are slightly smaller than their adjacent borders.

You probably already see a single div star in the making. The next step is to rotate the shapes.

Step 4: Rotate the Shapes

Each section of an element (:before, main, and :after) can be altered independent of its siblings. So next we rotate each shape to its unique position, using the transform property:

See the Pen Step 4: Rotate the Shapes by Float Nine (@floatnine) on CodePen.

Nothing magical here. I’ve rotated the main element thirty-five degrees clockwise with the “transform: rotate(35deg)” style rule . This rotated the :before and :after pseudo-elements thirty-five degrees as well, so next I rotated the :before element back to its initial position with “transform: rotate(-35deg)”. Finally I rotated the after element thirty-five degrees counter-clockwise with “transform: rotate(-70deg)”, which corrected for the thirty-five degrees it had been rotated clockwise, and then rotated it thirty-five degrees more counter-clockwise. Our shapes are now ready to be merged.

Step 5: Merge the shapes to create a single div star

The final step is to move the shapes together. Utilizing the absolute relative positioning technique we employed earlier, we just need to position the :before and :after pseudo-elements to rest on top of the main element:

See the Pen Step 5: Merge the Shapes by Float Nine (@floatnine) on CodePen.

And voila! Our single div star is complete!

The coolest thing about what I’ve shown you here today is that you can use the combination of border generated polygons, rotation, and the :before and :after pseudo-elements to create a huge array of different shapes, from cut diamonds, to eight and twelve point starbursts, to chevrons, and so on. Using other CSS properties like box-shadows, skews, and border-radiuses allow you to make a ton more amazing shapes. Check out this CSS Tricks article to learn more.

Five Ways CSS Grid is Better Than Flex-box

1. It’s easier than ever to create two dimensional layouts

The biggest benefit to using grid over flex-box is that grid allows you to style layouts in two dimensions, quickly and easily. Say you want to create a layout like this:

See the Pen 1.1 Layout Model by Float Nine (@floatnine) on CodePen.

You can achieve this with flex-box, but the solution is either hacky and rigid, or requires several flex-boxes working in tandem. Instead, take a look at how it can be laid out in grid:

See the Pen 1.1 Layout Model by Float Nine (@floatnine) on CodePen.

See that grid-template-areas property? Those four short lines determine the layout of the grid. Then the grid-area properties map items to elements. It couldn’t be easier.

2. Easily rearrange the layout of your grid without altering the CSS

Take another look at the layout in the above example. Now look at this:

See the Pen Standard Grid in CSS Grid with Cells Rearranged by Float Nine (@floatnine) on CodePen.

These changes were made without altering the HTML at all. That’s the power of grid. While in flex-box you could rearrange the order of items in a flex container, with grid you can change the size, shape, and location of elements with just a line or two of CSS. Combined with media queries, this is a really powerful feature.

3. Grid’s auto-fit keyword

This was a big pet peeve of mine in flex-box. When a row of items spills into the new row, flex-box leaves uneven white space at the end of the initial row. Resize the red container to see what I mean:

See the Pen Resize Flex No Grow by Float Nine (@floatnine) on CodePen.

You can remedy this with flex-grow, but then you have another problem. The bottom row stretches its items to fill up the empty space:

See the Pen Resize Flex Grow by Float Nine (@floatnine) on CodePen.

With some help from grid’s auto-fit keyword, the items in each row and column work together to create an eye-pleasing, two-dimensional layout:

See the Pen Resize Grid Auto-Fill by Float Nine (@floatnine) on CodePen.

For more information about auto-fit and its partner auto-fill, check out this excellent article on CSS-Tricks.

4. Auto calculate remaining space with the fr unit

One of the most powerful features of grid is the fr unit. Fr stands for fraction. Its power lies in its ability to calculates available height and/or width for you. It takes into account the fixed widths/heights, percentages, as well as the proportional fr values of all the other elements in the row or column. Then it determines how much space is needed to fill the remaining width or height:

See the Pen wXgXYy by Float Nine (@floatnine) on CodePen.

Here we have a first column that is one third the width of the second (1fr vs 3fr), and three rows of varying heights (2fr, 1fr, and 3fr). Frs are responsive, so as the viewport size changes, they will auto-adjust for you. Not only that, but you don’t have to factor in margins and borders like you did when using percentages.

5. Comes with its own functions: repeat and minmax

Remember that auto-fit example from reason 3? Let’s take a look at what’s happening under the hood:

See the Pen Comes with its own functions by Float Nine (@floatnine) on CodePen.

Specifically, look at the grid-template-columns property. In addition to auto-fit, it uses a repeat function and a minmax function. These are currently grid exclusive functions that help us do cool things. In this instance, the repeated items shrink and grow along with the container, but when they hit < 60px in width, they wrap to the next line. The minmax function is equivalent to setting a min-width and max-width for each item. Resize the grid container to see this in action. Grid’s units, keywords, and functions work together flawlessly, and can be mixed and matched in lots of different ways.

Conclusion

So there you have it. Grid is an awesome technology that I recommend you dive into, if you haven’t already. It already has widespread support, and will become more and more popular as time goes on. If you’re looking for an online resource to start learning grid (or fill in your existing knowledge), A Complete Guide to Grid on CSS-Tricks is a great resource. I’m not affiliated with the site, by the way, I just like their work.

And keep in mind, grid is not going to replace flex-box. The two technologies actually complement each other very nicely. And often times flex-box is the best choice for a given task. But for a lot of your layout needs, grid really is the best solution. So my advice is to get familiar with grid at your earliest convenience. Its not only useful, its a lot of fun.

The Ten Best CSS Named Colors

Although a full range of colors have been available in CSS since the early days, most of the named colors we have today are a slightly newer phenomenon. Some of the 124 “non-standard” named colors that rolled out with CSS3 are wacky. Some are just plain inaccurate. But the fact remains, they are still much easier to remember than most Hex and RGB codes. So without further ado, here are the ten best CSS named colors that you should add to your palette today:

10. Dodger Blue

See the Pen ERNZGo by Float Nine (@floatnine) on CodePen.

The name for this color was originally coined by LA Dodger’s team manager and baseball great, Tommy Lasorda.  It was added to the X11 User Interface System by Paul Raveling in 1989, and a few decades later ported over to CSS3 along with the other 124 non-standard colors. Although Dodger Blue can be found throughout Dodger Stadium, the blue on the actual Dodger’s uniform is a little darker: #005A9C.

9. Tomato

See the Pen WyoRPr by Float Nine (@floatnine) on CodePen.

This one kind of speaks for itself. Tomato is a nice, neutral orange-red color, and it actually looks like the thing it’s named after. Soothing and unoffensive as a bowl of soup, it is, also like a bowl of soup, sometimes exactly what you need. Tomato pairs well with lots of other colors too. All great reasons why it is one of the best CSS named colors.

8. Papaya Whip

See the Pen bKBgZd by Float Nine (@floatnine) on CodePen.

Like tomato and Dodger blue, papaya whip was originally part of the X11 User Interface System. It’s not a particularly remarkable color, just a standard looking beige. This one makes the list because it has one of the kookiest names, it’s practical, and most importantly, it’s just plain fun to write.

7. Light Sea Green

See the Pen mKORvg by Float Nine (@floatnine) on CodePen.

Light sea green not only has a great, overly verbose name, it strikes a number of perfect balances. It’s not quite blue and not quite green. Not exactly natural looking, and not too artificial. Not too bright, and not at all dull. There are actually four varieties of sea green amongst the web colors, and light sea green is the only one in the “Cyan Colors” section, making it one of the best CSS named colors.

6. Gold

See the Pen MXbJRm by Float Nine (@floatnine) on CodePen.

Funny thing about the named colors ported over from from X11, the programmers really didn’t include a good amount of well saturated yellows. Light yellow is way too pale, and yellow itself is too bright. So gold makes the list at number 6 in the best CSS named colors, as a serviceable alternative. Hopefully if the W3C ever revises the named colors again, they will add a few more usable yellows.

5. Chartreuse

See the Pen xzRgej by Float Nine (@floatnine) on CodePen.

Chartreuse is named after a popular French liqueur of the same name. The liqueur is more of a pale apple-green color, and the brighter web version was formulated in 1987 as an X11 color. With a hexadecimal code of #99FF00, chartreuse sits on the color spectrum exactly halfway between green and yellow, and is one of the bolder of the best CSS named colors.

4. Indigo

See the Pen YvpNgB by Float Nine (@floatnine) on CodePen.

Indigo is a nice satisfying deep purplish-blue, and makes the list at number four of the best CSS named colors. It is named after indigo dye, but the web color indigo is a little more violet and a little less blue than its natural counterpart. Perfect for when you need a solid purple color, without too much of a red tint.

3. Deep Sky Blue

See the Pen GGNrPa by Float Nine (@floatnine) on CodePen.

Besides having a descriptive name, deep sky blue is one of the more eye catching colors on the named colors palette. A little lighter than Dodger blue, deep sky blue is part of a three member family that includes sky blue and light sky blue. Originally called capri in the “real world,” the name deep sky blue was coined by the X11 programmers in the late 80s, and it’s stuck ever since.

2. Dim Gray

See the Pen Pabjzx by Float Nine (@floatnine) on CodePen.

Every web developer needs a few grays in their palette. Not only does dim gray have a cool name, but it’s a great “darker gray” tone. It’s darker than both gray and dark gray (gray is actually darker than dark gray, thanks to confusion amongst the X11 programmers, but that’s another story). Unlike some of the other “grays” on the named colors list, dim gray is a true gray color, meaning it has equal parts red, green and blue. Perfect for solid gray backgrounds that aren’t too dark or too light.

1. Orange Red

See the Pen vrygbb by Float Nine (@floatnine) on CodePen.

We round off the list with the eye-catching orange red. What can be said about this one, except that it makes the list because it’s just so pleasing to the eye. Bright and saturated, but not obnoxious. A little more red than orange, this one is perfect when you want a solid color that pops and isn’t common or boring. Pairs well with lots of other colors.

So there you have it! Ten great named colors to add to your palette. If there is an overall theme, it’s that these colors strike a balance between eye-catching and practical (except maybe for chartreuse). Incorporate them into your next web project, or just show off your named colors skills to your friends and colleagues. Hopefully too, this article will save you a trip to Google the next time you’re looking for the right web color. Forget hex codes! Named colors to the rescue!

 

How ems Work in CSS – Nailing it Down

Many developers go for years without knowing exactly how ems work in CSS. I blame this partly on the internet. It’s hard to find articles that properly and concisely explain what they are and how they work. As a result, developers often forgo them for pixel or percentage values when setting heights and widths in their CSS. This is a mistake, because ems are a useful tool to have. So if you don’t know exactly what ems are, and how they behave in different scenarios, this article will answer that for you.

Flags with Sky Background

How Ems Work in CSS – A Working Definiton

At the time of writing this article, I googled “How ems work in CSS” and I had to search five results down to this Sitepoint article to get a satisfactory answer. Here is the meat of the definition, as per the article:

“In CSS, an em unit is equal to the computed font-size for the element to which the em is applied.”

Okay, this is a pretty good explanation. It should be pinned to the top of the Google results. We all know what font size is, and this definition makes clear sense. Since a lot of us are visual learners, let’s look at a couple examples to drive the point home. First, take a look at this Codepen:

See the Pen bKErPy by Float Nine (@floatnine) on CodePen.

A couple notes here. We have set the height and width of the body element to 200px and given it a blue border. The .plane div inside of it has a width and height of 50%. As expected, this width and height equals 100px, or 50% of 200px. Now lets change the width and height of the .plane div to ems:

See the Pen MXKEvJ by Float Nine (@floatnine) on CodePen.

What happened? Well, the .plane div now has a height and width of 1em, which is equal to its font size, in pixels. Since we haven’t set a font size for the .plane div, the browser looks for the font size of its parent element, in this case the body element. As you can see in the CSS, we haven’t set a font size for the body element, either. So next, the browser looks for the font size of the html element. Since the html element has no set font size either, the browser essentially gives up. It stops trying to find a developer set font size, and it uses its default font size instead.

In this case, the default browser font size is 16px. So the browser determines that the font size of the .plane div is 16px, and sets the width and height of the div to 1em of 16px (1 x 16px = 16px width and height).

Traversing Up the DOM

The process the browser went through to traverse up the DOM and find the right font size is important to note, as it is a main source of confusion for developers trying to understand how ems work in CSS. Here it is explained in the Sitepoint article:

“When em units are declared on child elements that don’t have a font-size defined, they will inherit their font-size from their parent, or from another ancestor element, possibly going all the way back to the root element on the document.”

In the case of the Codepen above, the browser looks for a developer set font size first in the .plane div, followed by the body element, and finally the html element. In this case, since even the html element doesn’t have a set font size, the browser uses its default font size of 16px. Another way of saying this is that the .plane div inherits a 16px font size.

A Test To Lock it Into Memory

Let’s make one more update to our Codepen to make sure we know exactly how ems work in CSS. We’re going to give the body element an explicit font size:

See the Pen PaZJEM by Float Nine (@floatnine) on CodePen.

I did something here you usually don’t see. I set the font size of the body element to 100px. Too big for most designers’ typographical needs, but it demonstrates my point well. The .plane div now has a width and height equal to 100px, or 1em (1em = 1 x 100px = 100px). As you would expect, the .plane div takes up half the height and half the width of the body element.

So that’s it. An element with a height or width in ems will match the height or width of it’s own font size multiplied by the number of ems specified. If the developer hasn’t set a font size, the browser traverses up the DOM to the element’s parent, grandparent, etc, until it finds a set font size. If the developer hasn’t set a font size for any of these elements either, the browser will use its own default font size, usually 16px. This is the same as saying that the element’s inherited font size is 16px. 1em will equal 16px, 2ems will equal 32px, 3ems will equal 48px, etc. So now you know, once and for all, how ems work in CSS.

Readable Code is Better Than Concise Code

When coding in a competitive environment, programmers often try to outgun each other by writing code that’s as compact as possible. But conciseness is not always a good thing in programming. In fact, readable code is almost always better than concise code.

If anyone knows the name of this artist, leave a comment below and I will attribute them (I couldn’t find them)!

Tell me if you’ve been in this situation before: you write a piece of code to add to your company’s application. You push it up to the shared repository, satisfied that you’ve done a good job. But before the head coder adds it to the application, he or she “revises” it. They reduce the variable names to single letters like “a” and “b,” and replace lines of code with helper functions. When they’re done doing that, they combine lines, and add in hacky tricks to make it all work. All this in the name of saving space and making things concise. What’s left looks technically impressive, but it’s no longer readable code.

From a philosophical standpoint, your code may have been better to begin with. In fact, it probably was.

This can be discouraging. The revised code is unrecognizable, as if your contribution has been written right out of it. The changes feel like a critique of your skills. Often times, from a philosophical standpoint at least, your code may have been better to begin with. In fact, it probably was. You wrote a block of readable code, and after the edits, well, it’s hard to see what it does.

Sometimes More is More

Compact code isn’t necessarily a bad thing, but readable code is better. If your code is too compact, other programmers will have trouble understanding it. Hell, YOU will have trouble understanding it. Say you come back to it after a few months to add a feature or refactor. It may take you a minute just to reacquaint yourself and remember what you did.

Take a look at the following code:

This dictionary in Python contains a first name and a last name that we want to print out in a message. But we don’t know that the “first name” and “last name” keys exist (imagine that we don’t have direct access to the dictionary, or that it’s dynamically created). So we’ll have to check for them before we write the message.

Code That is Too Long

Something like this will work:

Pretty straightforward, right? We check that the keys exist in the dictionary, assigning them to variables if they do. Then we append them to a string, and print the string. This is certainly a block of readable code. Of course, it’s also bait for an edit-happy colleague, because it’s not exactly concise.

Code That is Too Concise

You can make it a lot more concise, like this:

This code does what the previous snippet did in thirteen lines, in only one. Instead of storing anything in variables, we’re printing the message straight out, using ternary (or conditional) operators. Since Python has trouble with two ternary operators on the same line, we’ve put them into a join() function, that uses a single space as a separator (the ‘ ‘ before the .join function name).

But hang on…this is no longer readable code. If you didn’t know what this code did beforehand, it would have taken some effort to parse. It’s not that it’s too hard to deconstruct, given a little time, but consider a hundred lines like this. Things would get tiring quickly.

The Solution: Readable Code

If a line of code appears too compact on first read-through, consider splitting it up a bit. Let’s try rewriting the code one more time, this time making it concise, while still readable:

There we go. We’ve reduced the snippet down to three lines, which is good. But more importantly, it’s still readable code. In some ways, actually, it’s easier to read than the first example. Our two ternary operators are on their own lines, giving them some breathing room. This means that we don’t have to strain to see where they start and stop. Finally, the results are plugged into a print statement, and we can easily see where the variables came from.

If a line of code appears too compact on first read-through, consider splitting it up a bit.

As I’ve hopefully demonstrated here, readable code is always preferable to compact code. You may save some memory and speed up a program by cutting down on lines, but unless you’re programming for embedded systems, or you’ve scaled to global proportions, it won’t matter much. It’s a lot more important to that your code is understandable. So don’t stress yourself out making your code as terse as possible, focus on readable code instead!