We do a couple straightforward things in step 2. First we add a background color to each of the three main elements. Second, we give the header and footer a minimum height so when we apply the flexbox they will stay static (Once display:flex is applied in step 3, min-height can be replaced with flex-basis).
Step 3 is crucial because here we apply display:flex to the body element, which we will see will give the footer its sticky appearance in step 3. We’ve also set the flex-flow to column, because the header, main, and footer sections need to be stacked on top of each other in a single column.
Finally, we’ve added some styling to the textarea element to make things look more like an actual webpage.
Step 4: Add flex-grow to the main section
Finally, we give the body and html elements a 100% height, and set main to flex-grow:1. Setting main to flex-grow:1 means that the body container (the flexbox) will expand to at least the height of the viewport on load. Giving main a setting of flex-grow:1 means that it will expand to fill the middle section of the container that the fixed height header and footer don’t. In tandem, this will mean that the direct children of the body tag (the header, main, and footer sections) will always fill at least the height of the viewport, and will expand as needed.
See how the star hovers up and down as suspended in air? That’s CSS animation at work. Now hover over it with your mouse. See how it spins? That’s a CSS transition. Transition and animation are very similar, the main differences being you can trigger transitions on user input (like mouse hover), while animations occurs on page load and can be fine tuned a bit more. They also work in tandem with each other, to create ever more automagical effects.
Linear and radial gradients let you design and create really cool background effects with just a few lines of code. You can make your gradients as simple or complex as you want by using multiple colors, repeated patterns, blending colors or creating hard color stops, and stacking gradients on top of images or even other gradients to create complex effects. There is a ton of creative potential with gradients, and the fact that they function like background images means that they don’t interfere at all with the rest of your layout.
Take a look at the list items above. Each has a different color, yet no classes or ids have been assigned to the elements. That’s because the :nth-child pseudo-selector is being used to target specific elements in the list. For example, li:child(5) selects the fifth list item, while li:child(even) selects every evenly numbered one.
The really automagical part of :nth-child expressions though is found in the use of expressions, which are short algebraic phrases that the browser interprets when the page is rendered. “n” here is an algebraic variable that starts at zero and counts up in increments of 1. For an example, here’s how we calculate the expression 3n + 4 (aka li:nth-child(3n + 4):
...repeatuntilwe reach the endofthe list...
For even more automagical effects, use negative factors of n to count up the list of items instead of down. Here is how li:nth-child(-1n + 3) is interpreted by the browser:
...stop,we've reached the beginning of the list...
2. Centering Elements with Flex-Box
If you’re not already using this centering technique, I recommend that you take a couple seconds to learn it here. It will save you a ton of time in the long-run.
For ages, centering items in their parent containers was more difficult than it should have been. We had to rely on hacky solutions like absolute positioning, negative margins, carefully calculated fixed length positioning, and other hacks like “transform: translateY(-50%)”. Then flex-box came along and made centering possible with two declarations:
When combined, “display: flex” and “margin: auto” do perfectly what developers have been hacking at for years. What’s even cooler is that this technique is completely responsive, as “margin:auto” item stays centered in flex-box no matter the width or height of the container. Flex-box can do a lot more than this, but this centering technique is an automagical feature that is worth hilighting.
Transform allows you to rotate, skew, and scale elements on your webpage. Combined with transition, you can achieve some really cool effects, like the card flipping demo above. To learn how to create flippable with CSS transform, check out this article.
That’s it for now. Stay tuned for more features and automagical CSS tricks in the future.
With some basic html, we’ll first create three divs: a container div with the class “card”, and two inner divs with classes “front” and “back”. Make sure that the .front div appears before the .back div:
I’ve given the back card some text and gave it a display type of flex, so I can center the text with align-items and justify-content. Also, both sides of the card have their own background color, and I’ve given each a border-radius of 14px to mimic rounded edges. Finally, I’ve given both .front and .back a fixed width and height.
Giving the back and front sides of the card a position of absolute will place them on top of each other. We then give the .back side a declaration of backface-visibility: hidden. This is so when the .back side is rotated 180 degrees (showing its backface), we only see the .front side. This video shows how this all works:
Here we’ve added a hover state to .card, and added two declarations of type transform:rotateY to the .front and .back sides. When the card is hovered over, the .front side gets flipped over 180 degrees, and the .back side, which is already flipped over 180 degrees, thanks to step 2, gets flipped back to its original state of 0 degrees.
Step 5: Add a transition to make everything smooth
To really get the feeling of a 3D card being flipped, we need to add the transition property. This allows us to animate transform:rotateY in a smooth manner.
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.
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:
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‘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 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!
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:
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 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:
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:
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:
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:
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:
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.
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:
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:
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:
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.
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.
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:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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!
CSS is a simple technology, right? Not exactly. Many web developers know it well enough to make regular style updates to a website. But to master CSS takes more than practice, it takes an effective strategy.
Recently I came across this article on Stack Overflow about how to make a div the same height as the browser window. The top answer is mercifully simple – apply the 100vh rule:
vh stands for viewport height, the height of the drawable region of a browser window. This is a cool trick, but it’s not always what we want to achieve. For example, if the div you are applying 100vh to is inside another div with a defined height, it can throw off the layout. Here’s an example, where the parent div has a green border:
The overflow of the #inner div makes it appear that something unintended has happened in the layout. So 100vh might not always be ideal. You could use 100% height instead, which will make the div as tall as possible, without exceeding the height of its parent element:
You might be thinking at this point, “That’s starting to get too complicated. What if I can’t make all of a div’s parent elements 100% height? It’s much easier to use the 100vh trick.” I would agree with you. This is a common problem people run into when they try to master CSS. Any given rule seems to only work some of the time. It seems like you’re left with one of two choices:
Memorize one or two techniques for each scenario and limit your HTML markup to always accommodate those techniques.
Don’t worry about the markup, whenever you come across a problem with styling, just noodle around in CSS until you get your desired effect.
Neither one of these strategies is ideal, for obvious reasons. The best answer is that you need to learn multiple ways to achieve any given effect, and know when and why to apply each one. This principle can be applied to thousands of layout issues: centering elements relative to each other, creating “sticky” footers and columns of equal heights, working with background images, and a myriad of everyday issues like lining elements up next to each other and repositioning elements with relative and absolute positioning.
The good news is, you don’t need to be able to list the different techniques off the top of your head, to begin to master CSS. Just try to approach CSS problems with this philosophy in mind. You will be way ahead of the game.
There is some CSS at the bottom of the window (hidden) that determines the size and shape of the two divs. Ignore that. What we are focusing on here is the positioning style rules, shown in .circle and .rectangle.
In the HTML (seen if you click the “HTML” button) you can see that the circle is clearly inside the rectangle. But because of the circle’s absolute position, with a bottom and right value of 0px, it is stuck to the bottom of the screen. Now, let’s add one style rule to the .rectangle class:
Pretty cool, huh? By adding the position of relative to the rectangle, we’ve completely changed the design layout of the page. Now the circle sits in the bottom-right of the rectangle, not the bottom-right of the page itself. Think of it like this: the circle is now positioned absolute bottom-right, relative to the rectangle.
And it’s really that simple. You can use this trick to position almost any element relative to its parent container.
Leave a comment below letting me know what you think, and check out my Twitter feed here.