Make a CSS Dropdown Menu in Five Steps

Step 1: Create the HTML

If you think about it, a menu is nothing more than a list of hyperlinks, so an unordered list with anchor tags works perfectly. Here we’ve created a list with three main items, the last one containing three sub-items:

See the Pen Make a Dropdown Menu in Five Steps – Step 1 by Float Nine (@floatnine) on CodePen.

Step 2: Make the top-level menu flexible

This step involves setting the top level ul element to display: flex, and giving it’s children, the top level li’s, a flex-grow of 1, so they expand to the full width of the viewport. Now we have a horizontally oriented, responsive, and flexible menu. To make the flex-box layout look correct, we’ve also removed the default margin and padding from the ul and li elements, and we’ve removed the bullet points from the list items:

See the Pen Make a Dropdown Menu in Five Steps – Step 2 by Float Nine (@floatnine) on CodePen.

Step 3: Add color and dimension

Before we add the dropdown functionality, we need to give the menu some style. There are a number of small steps here, but they all relate to each other, so I think its easiest to keep them together. See the /*Step 3*/ code in the code window to follow along:

Color: The top list items have been given a background color of dimgray, with a margin-right of 2px to distinguish them. The secondary list items have been colored dodgerblue and tomato, with top margins of 2px. In addition, the color of the anchor tags has been changed to white and the anchors have been given some basic style.

Dimension: Each anchor tag has been given a padding of 1em, and set to display: block to show the padding. In addition, we’ve given the submenu’s ul tag (containing Item 3-1 through 3-3), a width of 100% and set it to position: absolute, which along with it’s parent li element set to position: relative, will allow it to flexibly stretch along with its parent, Item 3 (for more information on absolute relative positioning, see this article) .

See the Pen Make a Dropdown Menu in Five Steps – Step 3 by Float Nine (@floatnine) on CodePen.

Step 4: Add the dropdown effect

This step is relatively simple, but it deserves its own step, as it is where we give the menu its namesake functionality. We do this with only two declarations. First we give the submenu’s ul tag a display of none as default. Then we give it a display of block when its parent li element (i.e. Item 3) is hovered over.

See the Pen Make a Dropdown Menu in Five Steps – Step 4 by Float Nine (@floatnine) on CodePen.

Step 5: Add additional hover effects on the list items

To give the menu more of an interactive feel, the final step is to add hover effects to each of the list items. To do this I assigned rgba functions to the hover states of each item, with an opacity value of .7 (70% opaque). Again, the three declarations (one for each color) are at the top of the code window for visibility:

See the Pen Make a Dropdown Menu in Five Steps – Step 5 by Float Nine (@floatnine) on CodePen.

And that’s it. Hopefully this demystifies the process of creating a dropdown menu. You can use these principles to add as many menu items and effects as you want.

CSS Background-Size: Five Examples Explain It

One of the trickier hurdles when leveling up your CSS skills is learning the various options for background-size. There are so many values and value combos to work with that initially it’s even a little intimidating. You’ve got the contain, cover, and auto keywords. Then there are relative units like em and %, and absolute units like px and pt. And then there are all the combinations of relative units, absolute units, and the auto keyword. Instead of going through each possibility one by one, which would be a very long article, I’ve decided to cover five common values/value combinations that each attempt in their own way to solve the most common problem with background images: stretching the background image across its element’s canvas without distorting the image or cutting it in half. Along the way, you will learn how to compare and combine values to achieve 95% of your background-sizing goals.

For the purpose of this article, an element’s canvas is defined as the physical shape on the screen of the element that the background image is applied to, and is represented by the orange-red dashed border in the examples below.

Background-Size: Auto

The default background-size is auto, so it’s the first effect we see when we add the background-image declaration to our CSS, before we even declare the background-size (if we decide to declare it at all). The full value is auto auto, meaning auto width and auto height. You can declare it as simply auto because when a single value is assigned to the background-size property (unless the value is cover or contain), a second value of auto is implied. The first (or only) value is always assigned to the width of the background image, the second (or implied, auto) value is assigned to the height.

That’s how to declare the auto keyword, but what does it do? The answer is, auto automatically calculates the width or the height of a background image based on the length of the opposing dimension (width or height), while maintaining the aspect ratio of the original picture. The aspect ratio is simply the ratio of the width to the height of an element. For example, a rectangle that is 400px wide and 100px tall has an aspect ratio of 4:1.

So to reiterate, if width has a set length, the auto keyword (e.g. background-size: 100px auto) will give the image the image the height it needs to display undistorted. If both width and height are set to auto, the background picture is set to its initial width and height. That’s what we see here:

background-size: auto auto

The image is repeated to fill the canvas (the canvas is represented by the dashed orange-red border). When the image runs out of room, it is cut short. The problem is of course that we don’t want to use a repeating pattern, and we don’t want the image, or in this case images, to be cut off when they reach the edge of the canvas. So we need to move on from background-size: auto.

Background-Size: 100% 100%

Background-size: 100% 100% (100% width and 100% height) solves a couple of the problems we ran into with auto. It fills the element’s entire canvas with a single version of the image, and the image isn’t cropped at all. Of course the downside here is that the background image is distorted when its aspect ratio is different from the aspect ratio of the element’s canvas:

In the situations above, we end up with a stretched out, squished cat. That’s not what we’re after. But we’ve reached an interesting point in our journey. We’ve now found two value combos (Auto auto and auto 100%) that do some of the things we want them to, but not all. It’s time to combine them.

Background-Size: 100% Auto

This gets us a lot closer to our goal. 100% width and automatic height means that the background image is stretched to fill the width of the element’s canvas, and then its height is calculated on the fly (at page load and every time the browser’s viewport is resized), to maintain the original aspect ratio of the background image:

At this point you might be tempted to pack up and call it a day. If the element never changes its aspect ratio this would be fine. But chances are you want the element to change its height and width based on the height and width of the browser’s viewport. That’s where background-size: 100% auto runs into problems. Take a look at background-size: 100% auto when the element maintains same width, but has a taller height:

Now we can see what’s happening more clearly. Background-size: 100% auto leaves a gap at the bottom of the canvas when the element has a taller/skinnier aspect ratio. In the initial example, the element had a shorter/wider aspect ratio compared to the background image, but it wasn’t very noticeable because the image was simply cropped at the bottom (notice kitty’s collar was missing).

We can partly remedy the situation by setting another style rule, background-position, to center, but this will just center the background image vertically in the element’s canvas, leaving a gap above and below the image:

Side Note: If you can imagine, background-size: auto 100% (auto width and 100% height) will do the exact same thing, except that the background image will be expanded to fit the height of the element’s canvas, and then the width will be auto generated, either cutting off the side of the image or leaving white space to the side. Same problem, different perspective.

So background-size: 100% auto is the best value combo we’ve come across so far, but it still isn’t perfect. Our next logical step is to explore background-size‘s two remaining keywords, contain and cover.

Background-Size: Contain

Background-size: contain‘s unique ability is to make the background image, using its original dimensions, as big as possible without ever overflowing the element’s canvas (i.e. keeping it contained). If the image can fill the width of the canvas without the height overflowing, contain will give it a 100% width and auto height. If it can fill the height of the canvas without the width overflowing, contain will give it a 100% height with an auto width. Unless the aspect ratio of the canvas is identical to the aspect ratio of the background image, one and only one of these scenarios (100% auto or auto 100%) will be viable at a time.
Background-size: contain is perhaps easiest to understand with a couple visual examples. Here it is when the element’s canvas is shorter/wider than the background image:
And here it is when the element’s canvas is taller/skinnier than the background image:
The cool thing about contain is that it switches between these two modes on the fly. That is, as the element’s canvas is resized, contain will switch, as necessary, between the two above modes.
The beauty of contain is that it always gives us a complete, undistorted, large as possible background-image. That’s pretty good, when you considered how far we’ve come from background-size: auto. We can’t help it if the aspect ratio of the background image doesn’t match up with the aspect ratio of the element’s canvas, right? So background-image: contain might be as good a solution as any.
Well, there is one more background size value that arguably beats out contain, and that is cover. Let’s look at it next.

Background-Size: Cover

Background-size: cover combines the best of all the options we’ve looked at so far. It essentially does the opposite of contain, by filling either the width or the height of the element’s canvas, whichever causes the image to overflow the canvas on the alternate dimension. So if 100% width makes the image too tall for the canvas, it chooses that option. If instead, 100% height makes the image too wide, it chooses that instead.
The overflowed portion of the picture is cropped out, but we don’t tend to notice, especially with background-position: center center set:
I purposefully used this square shaped element canvas to show just how good background-size: cover is. Here, our rectangular background image has been set to cover a square shaped element canvas. Here, cover is assigning itself 100% height, with the width overflowing on the left and right (with a little help from background-position: center). The image is actually centered on the canvas, the cat’s head in the photograph just happens to be a little left-of-center in the original photo.

This is in my opinion and the opinion of many, as good a solution as any when faced with the problem of placing a background image on an element’s canvas. Especially when the canvas’s shape and size will change with the shape and size of the browser’s viewport. To fully understand how cover works, it was important that we went on the journey we did, seeing how cover uses techniques from 100% and auto sizing, and how it is similar to contain. Now that you’ve learned it, you know exactly how it acts in different situations, which is where you want to be as a CSS developer. You have leveled up in your knowledge of CSS, go forth with renewed confidence.

If you liked (or hated) the article, please leave your comments below. See you next time!

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.

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.

Streamlining Code (Without Fucking Things Up)

When people talk about streamlining code, usually they are talking about writing code that runs as fast as possible under heavy loads. Google’s search functionality, for example, handles millions of requests daily, so it’s to Google’s advantage to write the leanest, fastest code possible. Even a small bit of code, if written badly enough, could measurably slow down a production that large.

Of course most of the code we write doesn’t handle data at the volume Google does. But even if you’re just looping through a large file, it is useful to streamline your your code. Streamlining also tends to follow best practices, and makes your code easier to read, so doing so builds your skills as a programmer.

Take a simple task like opening a file and reading through its lines, one by one. Let’s say we want to streamline this. We might first look at something like this:

Seems pretty succinct. But without much effort, we can reduce this five line snippet to four, like so:

All we did here was collapsed lines 1 and 2. Moving the string stored in the file variable into the open() function. It’s arguable a little easier to read, and now the machine running it won’t have to store an extra variable in memory, only to retrieve it one line later. Also, the code is arguably just a little easier to read read. We could take things a step further, like this:

Now we’ve collapsed lines 1 and 2 again. That open() function returns a file object, which now, instead of being stored in a variable, is fed directly into the with statement. Okay, so our code is still legible, and we’ve eliminated another unnecessary variable. Can we take it one step further? Well, yeah. This is what we could do:

This works, and produces the same output as the previous snippets. But is it better? No. We’ve lost something here. The with statement has been taken out, and we’re jumping straight to the for loop. The with statement makes sure that the file object created by the open() function gets handled correctly if something goes wrong. It’s essentially like putting the code in a try/finally statement, where finally calls close() on the file object, no matter what happens. It’s the same as writing this:

To put it another way, we reached peak efficiency with out third iteration of streamlines:

It’s at this point that we’d made the code as small and resource light as possible, without losing any of it’s original functionality.

Now, this is not to say that this snippet is necessarily the ideal for any situation. Maybe you want to leave in some of those variables for a reason. Say you’re processing several files with the same snippet, and want to pass in the file names to the same file variable each time. Or maybe you just personally find the use of some extra variables makes your code more legible. That’s fine, and I wouldn’t argue with you at all. The point is to decide what works best for you, while taking into account the load the machine running the code has to deal with, and as a result, how quickly it can complete its job. If you are passing it a file that is only a thousand lines long, maybe reducing the code by a line or two won’t matter. If you’re passing in a thousand files that are a thousand lines long, however, it might be worth your while!