css basics – CSS-Tricks https://css-tricks.com Tips, Tricks, and Techniques on using Cascading Style Sheets. Tue, 28 Jun 2022 15:10:32 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 https://i0.wp.com/css-tricks.com/wp-content/uploads/2021/07/star.png?fit=32%2C32&ssl=1 css basics – CSS-Tricks https://css-tricks.com 32 32 45537868 My Dumbest CSS Mistakes https://css-tricks.com/my-dumbest-css-mistakes/ https://css-tricks.com/my-dumbest-css-mistakes/#comments Tue, 28 Jun 2022 15:10:31 +0000 https://css-tricks.com/?p=366484 We all make mistakes in our code. It happens! I know if I had one of those “Days Since Last Mistake” signs hanging over my desk, a big ol’ goose egg would be hovering above me all the time. It …


My Dumbest CSS Mistakes originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
We all make mistakes in our code. It happens! I know if I had one of those “Days Since Last Mistake” signs hanging over my desk, a big ol’ goose egg would be hovering above me all the time. It doesn’t have to be big mistakes, either. My clumsy self has committed small errors to repos ranging from typos all the way to complete npm module directories.

Whooooooops.

That’s one of the things I really love about CSS: it’s forgiving as heck. If it doesn’t understand a typo, it keeps looking up the cascade in search of a match. None of that stuff where one out of place characters breaks a site and takes no prisoners. But it’s still embarrassing when CSS mistakes pop up!

Like this one I find myself making way more times than I’d like to admit:

.element {
  display: flexbox; /* 🤦‍♂️ */
}

Or when I try setting a gradient without a background property:

.gradient {
  linear-gradient(45deg, rgb(50% 100% 90%), rgb(62% 85% 93%));
}

I hate how close X and C are on a keyboard because I can’t count how many times I’m blazing through something and mistake px for pc units.

.element {
  font-size: 16pc; /* I meant pixels! */
}

Another CSS mistake I catch every so often is one I know many other folks make because I spot it too often in blog posts with code snippets:

// This is not a CSS comment.
.element {
  /* This is a CSS comment. */
}

Have you ever forgotten to use var() around a CSS variable? I sure have.

.element {
  color: --primary-color;
}

Speaking of CSS variables, naming them is hard (like everything else) and I often use some incorrect version of a variable that I named!

:root {
  --color-primary: #FF5722;
  --color-secondary: #3E2723;
}

/* Much later on... */

.element {
  color: var(--primary-color); /* 🙃 */
}

Yes, I have indeed copied a snippet of CSS before only to have fancy quotes get in the way of making it work:

.element::before {
  content: “”; /* Should be "" */
}

And, yes, I have spent way too long figuring out those quotes were the culprit.

Looking at that last one reminds me that I sometimes forget to set the content property when I’m working with ::before or ::after. Which reminds me of how I’ve forgotten to set an element’s position before trying to offset it or change its z-index. Seriously, these things happen!

It’s hard talking about mistakes

Have you ever finished reading some blog post sharing some amazing trick and felt some sort of Imposter Syndrome? I think that’s largely because blog posts often mask the real work — and failures — that go into amazing tricks. As someone who reads posts like that for a living, I can tell you that many, if not the vast majority, go through many rounds of editing where potentially embarrassing mistakes are weeded out and smoothed over.

Even those ridiculously awesome articles have to fail before they get all those ooooos and ahhhhhs.

The same is true of any app, website, demo, or whatever you happen to come across. The chances any of them came out perfect the first time is next to nothin’.

But if I’m being totally honest with you, I’m often more amazed (and interested) in the journey it takes to accomplish something, warts and all. The journey is a glimpse into what it’s like to think like a front-end developer. That’s where real (and most valuable) learning happens.

And all of this is merely building up to what I really want to ask…

What are your dumbest CSS mistakes?

C’mon, we all know you’ve made some! Let us learn from them!


My Dumbest CSS Mistakes originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/my-dumbest-css-mistakes/feed/ 41 366484
The “C” in CSS: The Cascade https://css-tricks.com/the-c-in-css-the-cascade/ https://css-tricks.com/the-c-in-css-the-cascade/#comments Tue, 13 Nov 2018 15:01:24 +0000 http://css-tricks.com/?p=278596 Following up from Geoff’s intro article on The Second “S” in CSS, let’s now move the spotlight to the “C” in CSS — what we call the Cascade. It’s where things start to get messy, and even confusing …


The “C” in CSS: The Cascade originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
Following up from Geoff’s intro article on The Second “S” in CSS, let’s now move the spotlight to the “C” in CSS — what we call the Cascade. It’s where things start to get messy, and even confusing at times.

Have you ever written a CSS property and the value doesn’t seem to work? Maybe you had to turn to using !important to get it going. Or perhaps you resorted to writing the CSS inline on the element in the HTML file.

<div style="background:orange; height:100px; width:100px;">
  Ack, inline!
</div>

Speaking of inline styles, have you wondered why SVG editors use them instead of a separate CSS file? That seems kinda weird, right?

<svg id="icon-logo-star" viewBox="0 0 362.62 388.52" width="100%" height="100%">
  <style>
    .logo {
      fill: #ff9800;
    }
  </style>
  <title>CSS Tricks Logo</title>
  <path class="logo" d="M156.58 239l-88.3 64.75c-10.59 7.06-18.84 11.77-29.43 11.77-21.19 0-38.85-18.84-38.85-40 0-17.69 14.13-30.64 27.08-36.52l103.6-44.74-103.6-45.92C13 142.46 0 129.51 0 111.85 0 90.66 18.84 73 40 73c10.6 0 17.66 3.53 28.25 11.77l88.3 64.75-11.74-104.78C141.28 20 157.76 0 181.31 0s40 18.84 36.5 43.56L206 149.52l88.3-64.75C304.93 76.53 313.17 73 323.77 73a39.2 39.2 0 0 1 38.85 38.85c0 18.84-12.95 30.61-27.08 36.5l-103.61 45.91L335.54 239c14.13 5.88 27.08 18.83 27.08 37.67 0 21.19-18.84 38.85-40 38.85-9.42 0-17.66-4.71-28.26-11.77L206 239l11.77 104.78c3.53 24.72-12.95 44.74-36.5 44.74s-40-18.84-36.5-43.56z"></path>
</svg>

Well, the cascade has a lot to do with this. Read on to find out how styling methods affect what’s being applied to your elements and how to use the cascade to your advantage because, believe me, it’s a wonderful thing when you get the hang of it.

TL;DR: Jump right to the CSS order diagram for a visual of how everything works.

The cascade cares about how and where styles are written

There are a myriad of ways you can apply CSS rules to an element. Below is an example of how stroke: red; can be applied to the same element. The examples are ordered in ascending priority, where the highest priority is at the bottom:

<!-- Inheritance -->
<g style="stroke: red">
  <rect x="1" y="1" width="10" height="10" /> <!-- inherits stroke: red -->
</g>

<!-- Inline attributes -->
<rect x="1" y="1" width="10" height="10" stroke="red" />

<!-- External style sheet -->
<link rel="stylesheet" href="/path/to/stylesheet.css">

<!-- Embedded styles -->
<style>
  rect { stroke: red; }
</style>

<!-- Different specificity or selectors -->
rect { stroke: red; }
.myClass { stroke: red; }
#myID { stroke: red; }

<!-- Inline style -->
<g style="stroke: red"></g>

<!-- Important keyword -->
<g style="stroke: red !important"></g>

Inheritance? Embedded? External? Inline? Specificity? Important? Yeah, lots of terms being thrown around. Let’s break those down a bit because each one determines what the browser ends up using when a web page loads.

Elements can inherit styles from other elements

Both HTML and SVG elements can inherit CSS rules that are applied to other elements. We call this a parent-child relationship, where the element the CSS is applied to is the parent and the element contained inside the parent is the child.

<div class="parent">
  <div class="child">I'm the child because the parent is wrapped around me.</div>
</div>

If we set the text color of the parent and do not declare a text color on the child, then the child will look up to the parent to know what color its text should be. We call that inheritance and it’s a prime example of how a style cascades down to an element it matches… or “bubbles up” the chain to the next matched style.

However, inheritance has the lowest priority among styling methods. In other words, if a child has a rule that is specific to it, then the inherited value will be ignored, even though the inherited value may have an important keyword. The following is an example:

<div class="parent" style="color: red !important;">
  <div class="child">I'm the child because the parent is wrapped around me.</div>
</div>

See the Pen Child ignores inline inheritance with !important by Geoff Graham (@geoffgraham) on CodePen.

SVG inline attributes

For SVG elements, we can also apply styles using inline attributes, where those have the second lowest priority in the cascade. This means the CSS rules in a stylesheet will be able to override them.

<rect x="1" y="1" width="10" height="10" stroke="red" />
rect {
  stroke: blue;
}

See the Pen Stylesheet overrides SVG inline attributes by Geoff Graham (@geoffgraham) on CodePen.

Most SVG editors use inline attributes for portability; that is, the ability to copy some elements and paste them elsewhere without losing the attributes. Users can then use the resultant SVG and style its elements using an external stylesheet.

Stylesheets

Stylesheets are divided into two flavors: external and embedded:

<!-- External style sheet -->
<link rel="stylesheet" href="/path/to/stylesheet.css">

<!-- Embedded styles -->
<style>
  div { border: 1px solid red }
</style>

Embedded styles have the same priority as external stylesheets. Therefore, if you have the same CSS rules, ordering rules applies.

See the Pen Embedded styles override stylesheet rules by Geoff Graham (@geoffgraham) on CodePen.

All stylesheets follow ordering rules, where files that are defined later, will have higher priority than those defined earlier. In this example, stylesheet-2.css will take precedence over the stylesheet-1.css file because it is defined last.

<link rel="stylesheet" href="/path/to/stylesheet-1.css">
<link rel="stylesheet" href="/path/to/stylesheet-2.css">

Specificity or selectors

How you select your elements will also determine which rules are applied, whereby tags (e.g. <p>, <div>), classes (e.g. .my-class) and IDs (e.g. #myI-id) have ascending priorities.

See the Pen Specificity by selectors by Geoff Graham (@geoffgraham) on CodePen.

In the example above, if you have a div element with both .my-class and #my-id, the border will be red because IDs have higher priority than classes and tags.

*Specificity has higher priority than ordering rules, therefore, irrespective if your rule is at the top or bottom. Specificity still has higher priority and will be applied.

Ordering

CSS rules always prioritize from left-to-right, then from top-to-bottom.

<!-- Blue will be applied because it is on the right -->
<div style="border: 1px solid red; border: 1px solid blue;"></div> 

<style>
  div {
    border: 1px solid red;
    border: 1px solid blue; /* This will be applied because it is at the bottom */
  }
</style>

Inline styles

Inline styles have the second highest priority, just below the !important keyword. This means that inline styles are only overridden by the important keyword and nothing else. Within inline styles, normal ordering rules applies, from left-to-right and top-to-bottom.

<div style="1px solid red;"></div>

The important keyword

Speaking of the !important keyword, it is used to override ordering, specificity and inline rules. In other words, it wields incredible powers.

Overriding inline rules

<style>
  div {
    /* This beats inline styling */
    border: 1px solid orange !important;
    /* These do not */
    height: 200px;
    width: 200px;
  }
</style>

<div style="border: 1px solid red; height: 100px; width: 100px;"></div>

In the example above, without the important keyword, the div would have a red border because inline styling has higher priority than embedded styles. But, with the important keyword, the div border becomes orange, because the important keyword has higher priority than inline styling.

Using !important can be super useful, but should be used with caution. Chris has some thoughts on situations where it makes sense to use it.

Overriding specificity rules

Without the important keyword, this div border will be blue, because classes have higher priority than tags in specificity.

<style>
  /* Classes have higher priority than tags */
  .my-class {
    border: 1px solid blue;
    height: 100px;
    width: 100px;
  }
  
  div { 
    border: 1px solid red;
    height: 200px;
    width: 200px;
  }
</style>

<div class="my-class"></div>

See the Pen Classes beat tags by Geoff Graham (@geoffgraham) on CodePen.

But! Adding the important keyword to the tag rules tells the element to ignore the cascade and take precedence over the class rules.

<style>
  .my-class { border: 1px solid red; }
  
  /* The important keyword overrides specificity priority */
  .my-class { border: 1px solid blue !important; }
</style>

<div class="my-class"></div>

See the Pen !important ignores the cascade by Geoff Graham (@geoffgraham) on CodePen.

Overriding ordering rules

OK, so we’ve already talked about how the order of rules affects specificity: bottom beats top and right beats left. The surefire way to override that is to put !important into use once again.

In this example, the div will take the red border, even though the blue border is the bottom rule. You can thank !important for that handiwork.

<style>
  div { border: 1px solid red !important; } /* This wins, despite the ordering */
  div { border: 1px solid blue; }
</style>

<div></div>

See the Pen Important wins over ordering by Geoff Graham (@geoffgraham) on CodePen.

Visualizing the cascade

Who knew there was so much meaning in the “C” of CSS? We covered a ton of ground here and hopefully it helps clarify the way styles are affected and applied by how we write them. The cascade is a powerful feature. There are opinions galore about how to use it properly, but you can see the various ways properties are passed and inherited by elements.

More of a visual learner? Here’s a chart that pulls it all together.

Download chart

The “C” in CSS: The Cascade originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/the-c-in-css-the-cascade/feed/ 8 278596
CSS Basics: Fallback Font Stacks for More Robust Web Typography https://css-tricks.com/css-basics-fallback-font-stacks-robust-web-typography/ https://css-tricks.com/css-basics-fallback-font-stacks-robust-web-typography/#comments Fri, 16 Feb 2018 15:05:37 +0000 http://css-tricks.com/?p=266415 In CSS, you might see a ruleset like this:

html {
  font-family: Lato, "Lucida Grande", Tahoma, Sans-Serif;
}

What the heck, right? Why don’t I just tell it what font I want to use and that’s that? The whole idea …


CSS Basics: Fallback Font Stacks for More Robust Web Typography originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
In CSS, you might see a ruleset like this:

html {
  font-family: Lato, "Lucida Grande", Tahoma, Sans-Serif;
}

What the heck, right? Why don’t I just tell it what font I want to use and that’s that? The whole idea here is fallbacks. The browser will try to use the font you specified first (Lato, in this case), but if it doesn’t have that font available, it will keep going down that list. So to be really verbose here, what that rule is saying is:

  1. I’d like to use the Lato font here, please.
  2. If you don’t have that, try “Lucida Grande” next.
  3. If you don’t have that, try Tahoma.
  4. All else fails, use whatever you’ve got for the generic keyword Sans-Serif

So in what situation would a browser not have the font you’re asking for? That’s pretty common. There are only a handful of fonts that are considered “web safe”—meaning that it’s likely most computers visiting your site have that font installed and so the browser can use it. Think: Arial, Times New Roman, Courier, Georgia, Verdana, and a handful of others.

But most websites, these days, use custom web fonts. They load up a font as a resource (just as a website loads CSS itself as a resource, or an image, or JavaScript), then that font is available to use. The widely popular Google Fonts makes that pretty clear:

Load this font first, then you can use it in CSS.

Even when you load a font in this way, it’s still possible that the font doesn’t load. While Google is a generally very reliable host, you don’t control their servers; they do. Even more commonly, poor network connections may prevent a font from loading. In any font loading failure scenario, that’s another situation where a fallback font stack comes in handy.

Say I’m using the custom font Merriweather, and I set up my font stack like this:

html {
  font-family: Merriweather, Impact, Serif;
}

If Merriweather fails to load (or does load, but loads in such a way that it pops into place after it does—also known as FOUT), we’d see something like this:

A fallback font, in this case Impact, is seen. It’s incredibly awkward and doesn’t match the desired look at all.

Better to have your font fall back to something close to your top choice than to something totally unrelated! There is a fantastic tool by Monica Dinculescu call Font style matcher where you can play with fallbacks (that’s how I made that GIF above).

In the example above, we can see that Georgia is a much nicer fallback font than Impact is! The example is a little bit more fancy than just changing the font though. A couple of other settings were changed to make them match as closely as they are. To take advantage of that, you’re in font loading territory, which gets a bit complex. Your best bet there is consulting Zach Leatherman’s A Comprehensive Guide to Font Loading. In any case, picking a nice fallback font alone is worth doing.

Individual Characters

An interesting note about fallback fonts is that it’s not all-or-nothing. Individual characters in a font can fall down the stack if the specified font doesn’t have that character available.

As an extreme example, I’ll load the custom font Source Code Pro from Google Fonts but I’ll force it to only contain a handful of letters.

You can see in the first sentence how the fallback fonts took over and the end result wasn’t disastrous (like the second sentence) even though the custom font didn’t have some of the characters available. This will be more likely to happen with things like uncommon ASCII characters or even accented characters like ü, ā, or ñ.

As some side fun, here’s using that character fallback ability of CSS to do something unique:

More Reading


CSS Basics: Fallback Font Stacks for More Robust Web Typography originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/css-basics-fallback-font-stacks-robust-web-typography/feed/ 2 266415
CSS Basics: Styling Links Like a Boss https://css-tricks.com/css-basics-styling-links-like-boss/ https://css-tricks.com/css-basics-styling-links-like-boss/#comments Thu, 15 Feb 2018 14:45:49 +0000 http://css-tricks.com/?p=266368 You are probably well acquainted with how links looks without any styling at all. That blue. That underline. That's a link in it's purest form. But what if we want to change things up a bit? Perhaps blue doesn't work with your website's design. Maybe you have an aversion to underlines. Whatever the reason, CSS lets us style links just like any other element.


CSS Basics: Styling Links Like a Boss originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
The web was founded on links. The idea that we can click/tap a link and navigate from one web page to another is how surfin’ the web become a household phrase.

Links in HTML even look different from regular text without any CSS styling at all.

They are blue (purple if visited). They are underlined. That’s a link in it’s purest form.

But what if we want to change things up a bit? Perhaps blue doesn’t work with your website’s design. Maybe you have an aversion to underlines. Whatever the reason, CSS lets us style links just we can any other element. All we need to do is target the element in our stylesheet.

Want to use a different font, change the color, remove the underline and make it all uppercase? Sure, why not?

a {
  color: red;
  text-decoration: none;
  text-transform: uppercase;
}

Now we’re cooking with gas! But why stop there? Let’s look at a few other ways we can style links to complete the experience.

Links have different states, meaning they adapt when we interact with them on a webpage. There are three additional states of a link that are worth considering anytime we change the default style of links:

  • Link (:link): This is probably the least used, but it’s for styling <a> elements that have an href, rather than placeholder links.
  • Visited (:visited): The appearance of a link that the user has clicked on the page before when the mouse cursor is not on top of it. The styles you can apply to :visited are restricted for security reasons.
  • Hover (:hover): When the mouse cursor is place on top of the link without a click
  • Active (:active): When the link is in the process of being clicked. It might be super quick, but this is when the mouse button has been depressed and before the click is over.
  • Focus (:focus): Like :hover but where the link is selected using the Tab key on a keyboard. Hover and focus states are often styled together.

Note the order there is important:

  1. Link
  2. Visited
  3. Hover
  4. Active
  5. Focus

If you don’t do it in this order (imagine, say, your :visited style comes after your :hover style) the links won’t behave quite how you want. In my imaginary example there, the :visited style would override the :hover style, which is highly unlikely that is what you want. Focus is an accessibility feature, thus last because it is most important.

One way to remember the order is LOVE and HATE. that is L(ink)OV(isted)E / H(over)A(Active)TE.

Here is the same link we have been looking at. First, try hovering your mouse on top of it without clicking and notice that it becomes underlined. Then, click on the link, but leave your mouse button clicked down for a little bit to see how the active style changes the color of the link to black. Finally, let up on the mouse button and the link should turn purple before it’s technically been visited.

Links seem like a simple concept, but boy do they have a lot going on—and CSS gives us some incredible power to customize the experience!

While there is some debate about it, we can use CSS to make a text link look like a button.

Like other HTML elements, CSS can add background colors and padding to links that allow us to create the appearance of a button. Here’s our link using those techniques:

a {
  background-color: red;
  color: white;
  padding: 1em 1.5em;
  text-decoration: none;
  text-transform: uppercase;
}

Great! Now, let’s use the state-altering powers we learned in the last section to make our faux-button more interactive. We’ll make the button dark gray on hover, black on active, and light gray on visit:

a {
  background-color: red;
  color: white;
  padding: 1em 1.5em;
  text-decoration: none;
  text-transform: uppercase;
}

a:hover {
  background-color: #555;
}

a:active {
  background-color: black;
}

a:visited {
  background-color: #ccc;
}

Styling a link as a button and taking advantage of the states allows us to make some pretty cool effects. For example, let’s create a button with some depth that appears to get pressed when it’s active and pop back up when the click is done.

Oh, and Cursors!

We’ve gone into pretty great depth on style links, but there is one more component to them that we cannot ignore: the cursor.

The cursor indicates the position of the mouse on the screen. We’re pretty used to the standard black arrow:

The standard mouse cursor arrow

We can change the arrow to a hand pointer on it’s hover (:hover) state so that it’s easier to see that the link indicates it is an interactive element:

Using cursor:
pointer;
provides an interactive cue.
a:hover {
  cursor: pointer;
}

Whew, that’s much nicer! Now, we have a pretty fancy link that looks like a button with proper interactive cues.

Leveling Up

We’ve covered quite a bit of ground here, but it merely scratches the surface of how we can control the style of links. If you’re ready to level up, then here are a few resources you can jump into from here:

  • Mailto Links – A good reference for linking up email addresses instead of webpages.
  • The Current State of Telephone Links – Did you know you can link a phone number? Well, here’s how.
  • Cursor – The CSS-Tricks reference guide for customizing the cursor.
  • When to Use the Button Element – If you’re wondering about the difference between a link button and a traditional form button, then this is a good overview with suggestions for which is better for specific contexts.
  • Button Maker – A free resource for generating the CSS for link buttons.

CSS Basics: Styling Links Like a Boss originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/css-basics-styling-links-like-boss/feed/ 15 266368
CSS Basics: Using Multiple Backgrounds https://css-tricks.com/css-basics-using-multiple-backgrounds/ https://css-tricks.com/css-basics-using-multiple-backgrounds/#comments Wed, 14 Feb 2018 20:53:41 +0000 http://css-tricks.com/?p=266396 With CSS, you can control the background of elements. You can set a background-color to fill it with a solid color, a background-image to fill it with (you guessed it) an image, or even both:

body {
  background-color: red;
  background-image: 


CSS Basics: Using Multiple Backgrounds originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
With CSS, you can control the background of elements. You can set a background-color to fill it with a solid color, a background-image to fill it with (you guessed it) an image, or even both:

body {
  background-color: red;
  background-image: url(pattern.png);
}

Here’s an example where I’m using an SVG image file as the background, embedded right in the CSS as a data URL.

See the Pen background color and image together by Chris Coyier (@chriscoyier) on CodePen.

That’s just a single image there, repeated, but we can actually set multiple background images if we want. We do that by separating the values with commas.

body {
  background-image: 
    url(image-one.jpg),
    url(image-two.jpg);
}

If we leave it like that, image-one.jpg will repeat and entirely cover image-two.jpg. But we can control them individually as well, with other background properties.

body {
  background-image: 
    url(image-one.jpg),
    url(image-two.jpg);
  background-position:
    top right, /* this positions the first image */
    bottom left; /* this positions the second image */
  background-repeat:
    no-repeat; /* this applies to both images */
}

See how background-position also has comma-separated values? Those will apply individually to each image respectively. And then how background-repeat has only one value? We could have done two values in the same way, but by using just one value, it applies to both.

Here’s an example using four separate images, one in each corner, offset by a smidge:

See the Pen Example of multiple backgrounds by Chris Coyier (@chriscoyier) on CodePen.

It’s too bad you can’t rotate or flip background images or else we could have used just one. We can rotate and flip entire elements (or pseudo elements) though, so in cases like that, we can get away with using a single image!

See the Pen Flipping Image So You Can Use Just One by Chris Coyier (@chriscoyier) on CodePen.

Just a few other things to be aware of here:

  1. The stacking order of multiple background is “first is on top.”
  2. Gradients are applied through background-image, so they can be used as part of all this. For example, you could set a transparent gradient over a raster image.

See the Pen Tinted Image w/ Multiple Backgrounds by Chris Coyier (@chriscoyier) on CodePen.


CSS Basics: Using Multiple Backgrounds originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/css-basics-using-multiple-backgrounds/feed/ 13 266396
CSS Basics: The Second “S” in CSS https://css-tricks.com/css-basics-second-s-css/ https://css-tricks.com/css-basics-second-s-css/#comments Wed, 14 Feb 2018 14:14:24 +0000 http://css-tricks.com/?p=266529 CSS is an abbreviation for Cascading Style Sheets.

While most of the discussion about CSS on the web (or even here on CSS-Tricks) is centered around writing styles and how the cascade affects them, what we don’t talk a whole …


CSS Basics: The Second “S” in CSS originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
CSS is an abbreviation for Cascading Style Sheets.

While most of the discussion about CSS on the web (or even here on CSS-Tricks) is centered around writing styles and how the cascade affects them, what we don’t talk a whole lot about is the sheet part of the language. So let’s give that lonely second “S” a little bit of the spotlight and understand what we mean when we say CSS is a style sheet.

The Sheet Contains the Styles

The cascade describes how styles interact with one another. The styles make up the actual code. Then there’s the sheet that contains that code. Like a sheet of paper that we write on, the “sheet” of CSS is the digital file where styles are coded.

If we were to illustrate this, the relationship between the three sort of forms a cascade:

The sheet holds the styles.

There can be multiple sheets all continuing multiple styles all associated with one HTML document. The combination of those and the processes of figuring out what styles take precedence to style what elements is called the cascade (That first “C” in CSS).

The Sheet is a Digital File

The sheet is such a special thing that it’s been given its own file extension: .css. You have the power to create these files on your own. Creating a CSS file can be done in any text editor. They are literally text files. Not “rich text” documents or Word documents, but plain ol’ text.

If you’re on Mac, then you can fire up TextEdit to start writing CSS. Just make sure it’s in “Plain Text” mode.

If you’re on Windows, the default Notepad app is the equivalent. Heck, you can type styles in just about any plain text editor to write CSS, even if that’s not what it says it was designed to do.

Whatever tool you use, the key is to save your document as a .css file. This can usually be done by simply add that to your file name when saving. Here’s how that looks in TextEdit:

Seriously, the choice of which text editor to use for writing CSS is totally up to you. There are many, many to choose from, but here are a few popular ones:

You might reach for one of those because they’ll do handy things for you like syntax highlight the code (colorize different parts to help it be easier to understand what is what).

Hey look I made some files completely from scratch with my text editor:

Those files are 100% valid in any web browser, new or old. We’ve quite literally just made a website.

The Sheet is Linked Up to the HTML

We do need to connect the HTML and CSS though. As in make sure the styles we wrote in our sheet get loaded onto the web page.

A webpage without CSS is pretty barebones:

See the Pen Style-less Webpage by Geoff Graham (@geoffgraham) on CodePen.

Once we link up the CSS file, voila!

See the Pen Webpage With Styles by Geoff Graham (@geoffgraham) on CodePen.

How did that happen? if you look at the top of any webpage, there’s going to be a <head> tag that contains information about the HTML document:

<!DOCTYPE html>
<html>
	<head>
		<!-- a bunch of other stuff -->
	</head>

	<body>
		<!-- the page content -->
	</body>

</html>

Even though the code inside the <head> might look odd, there is typically one line (or more, if we’re using multiple stylesheets) that references the sheet. It looks something like this:

<head>
  <link rel="stylesheet" type="text/css" href="styles.css" />
</head>

This line tells the web browser as it reads this HTML file:

  1. I’d like to link up a style sheet
  2. Here’s where it is located

You can name the sheet whatever you want:

  • styles.css
  • global.css
  • seriously-whatever-you-want.css

The important thing is to give the correct location of the CSS file, whether that’s on your web server, a CDN or some other server altogether.

Here are a few examples:

<head>
  <!-- CSS on my server in the top level directory -->
  <link rel="stylesheet" type="text/css" href="styles.css">

  <!-- CSS on my server in another directory -->
  <link rel="stylesheet" type="text/css" href="/css/styles.css">

  <!-- CSS on another server -->
  <link rel="stylesheet" type="text/css" href="https://some-other-site/path/to/styles.css">
</head>

The Sheet is Not Required for HTML

You saw the example of a barebones web page above. No web page is required to use a stylesheet.

Also, we can technically write CSS directly in the HTML using the HTML style attribute. This is called inline styling and it goes a little something like this if you imagine you’re looking at the code of an HTML file:

<h1 style="font-size: 24px; line-height: 36px; color: #333333">A Headline</h1>
<p style="font-size: 16px; line-height: 24px; color: #000000;">Some paragraph content.</p>
<!-- and so on -->

While that’s possible, there are three serious strikes against writing styles this way:

  1. If you decide to use a stylesheet later, it is extremely difficult to override inline styles with the styles in the HTML. Inline styles take priority over styles in a sheet.
  2. Maintaining all of those styles is tough if you need to make a “quick” change and it makes the HTML hard to read.
  3. There’s something weird about saying we’re writing CSS inline when there really is no cascade or sheet. All we’re really writing are styles.

There is a second way to write CSS in the HTML and that’s directly in the <head> in a <style> block:

<head>
	<style>
  	h1 {
  		color: #333;
  		font-size: 24px;
  		line-height: 36px;
  	}

  	p {
  		color: #000;
  		font-size: 16px;
  		line-height: 24px;
  	}
	</style>
</head>

That does indeed make the HTML easier to read, already making it better than inline styling. Still, it’s hard to manage all styles this way because it has to be managed on each and every webpage of a site, meaning one “quick” change might have to be done several times, depending on how many pages we’re dealing with.

An external sheet that can be called once in the <head> is usually your best bet.

The Sheet is Important

I hope that you’re starting to see the importance of the sheet by this point. It’s a core part of writing CSS. Without it, styles would be difficult to manage, HTML would get cluttered, and the cascade would be nonexistent in at least one case.

The sheet is the core component of CSS. Sure, it often appears to play second fiddle to the first “S” but perhaps that’s because we all have an quiet understanding of its importance.

Leveling Up

Now that you’re equipped with information about stylesheets, here are more resources you jump into to get a deeper understanding for how CSS behaves:


CSS Basics: The Second “S” in CSS originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/css-basics-second-s-css/feed/ 5 266529
CSS Basics: Using Fallback Colors https://css-tricks.com/css-basics-using-fallback-colors/ https://css-tricks.com/css-basics-using-fallback-colors/#comments Tue, 13 Feb 2018 14:25:41 +0000 http://css-tricks.com/?p=265404 Something you very much want to avoid in web design is unreadable text. That can happen when the background color of an element is too close or exactly the color of the text. For instance:

.header {
  background-color: white;
  


CSS Basics: Using Fallback Colors originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
Something you very much want to avoid in web design is unreadable text. That can happen when the background color of an element is too close or exactly the color of the text. For instance:

.header {
  background-color: white;
  color: white;
}

Which could lead to text that’s there, but invisible.

This is … very bad.

You’d never do that on purpose of course! The trouble is it can sneak up on you. For one thing, the default background-color is transparent, so without setting any background the background of an element is probably white.

More commonly, you’re using a background-image that makes the background a different color, and you’re setting white text on top of that.

header {
  background-image: url(plants.jpg);
  color: white;
}

Under perfect circumstances, this is all good:

But let’s take a look at what it looks like while the website is loading over a very common “Slow 3G” internet connection:

There’s no reason our dear visitor needs to wait to discover the incredible savings awaiting them this Sunday! Fortunately, a tiny bit of CSS solves this.

header {
  background-color: black;
  background-image: url(plants.jpg);
  color: white;
}

The black background color will ensure the white text will be visible while the image loads (or if it never loads at all!). Getting slightly fancier, we could use a color used in the image. I like a little app called Frank DeLoupe for helping me pluck a color from anywhere on my screen. Then I’ll use that color as the fallback color using the shorthand syntax for backgrounds:

header {
  background: #334C23 url(plants.jpg);
  color: white;
}

Much much better.

This kind of thing takes very little effort, improves your design’s resiliency and UX, and I think you’ll find becomes are part of your CSS muscle memory the more you write CSS.

Another related topic here, since we’re working with a photograph, is the idea of a “Progressive JPG.” Photoshop has the ability to save a JPG in this format. This changes how the displays as it’s coming across the network. Here’s a comparison video:

A low-res version of the image loads into place first, and it becomes higher quality as more of the image loads.

Perhaps a more desirable loading experience, but not a replacement for a fallback color.

Leveling up!

Images are one of the heaviest parts of websites, and loading techniques for them are a big topic in web performance. Here are some more related to things to think about:


CSS Basics: Using Fallback Colors originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/css-basics-using-fallback-colors/feed/ 6 265404
CSS Basics: The Syntax That Matters & The Syntax That Doesn’t https://css-tricks.com/css-basics-syntax-matters-syntax-doesnt/ https://css-tricks.com/css-basics-syntax-matters-syntax-doesnt/#comments Mon, 12 Feb 2018 14:28:08 +0000 http://css-tricks.com/?p=265703 When you’re starting to play around with CSS at the very beginning, like any other language, you have to get used to the syntax. Like any syntax, there are a bunch of little things you need to know. Some …


CSS Basics: The Syntax That Matters & The Syntax That Doesn’t originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
When you’re starting to play around with CSS at the very beginning, like any other language, you have to get used to the syntax. Like any syntax, there are a bunch of little things you need to know. Some characters and the placement of them is very important and required for the CSS to work correctly. And some characters are more about clean looking code and generally followed standards but don’t matter for the CSS to work.

First, so we have the terminology down:

A CSS ruleset consists of a selector and delcaration(s) wrapped in curly braces.

Important: Braces

All CSS rulesets must have opening and closing curly braces:

braces.header { padding: 20px;}.header padding: 20px;}.header { padding: 20px;}.header padding: 20px;

If you miss the opening brace, CSS will keep reading as if the next bit of text is still part of the selector. Then it’s likely to find a character like ; which are invalid as part of a selector and break. Breaking likely means it will screw up itself and the next ruleset, and recover after that.

Missing a closing brace is a bit worse in that it’s likely to mess up the rest of the entire CSS file unless it somehow finds a double closing brace and can resolve that first missing one.

Overall point: braces are very important!

Preprocessing languages like Sass and Less offer a syntax feature called nesting. This can be convenient, but note that when these preprocessors run and produce CSS, that nesting is removed because CSS by itself doesn’t support that. If you copy nested CSS into regular CSS, you’ll have problems with the braces.

Sometimes Important: Spaces

There are just a few places that spaces are important in CSS. One of the most important is in selectors. One space in a selector means you’re selecting descendants of the previous part of the selector. The selector body p means “select p elements that are descendants of the body element”. That space means a lot. Hopefully it’s clearly different than bodyp which won’t select anything (there is no <bodyp> element). But it’s not different from body p. Multiple spaces mean the same as one space.

spacesbody ul libodyulli.header .title.header .title.header .title.header.title=

You can’t put spaces in properties, function names, or anywhere you name things. Adding spaces in those situations effectively changes the names, breaking them.

spaces-3background-image: url(tiger.jpg);background – image: url(tiger.jpg);background-image: url (tiger.jpg);@keyframes goRoundAndRound { }@keyframes go-round-and-round { }@keyframes go round and round { }:root { –theme main: red; –theme-second: red;}body { background: var(–theme main); background: var(–theme-second);}

Other than that, spacing doesn’t matter much in CSS.

spaces_1.header { padding: 20px;}.header { padding:20px; } .header {padding: 20px; }.header{padding: 20px; }.header{ padding: 20px;}.header{padding:20px;}

I’d encourage you to be consistent with your spacing, and produce clean and readable CSS. You might want to reference some CSS style guides out there for some formatting best practices.

Even the !important rule in CSS, which comes after a the value in a delcaration like body { background: white !important; } doesn’t have any spacing requirements. It could have any amount of space before it, or none.

The removing of space in CSS is actually a best practice for performance, so you might notice that when peeking at the raw CSS of websites in production.

You’re better off leaving that minification of CSS to a tool that processes your CSS for you, leaving the original alone. We’ll have to cover the options for that in other post.

Mostly Important: Semicolons

Each declaration in a ruleset (a property and value pair) ends in a semicolon. That semicolon is required, otherwise CSS will keep reading the next property as if it’s part of the value of the previous declaration.

semicolons.header { padding: 20px; max-width: 600px; background: black; color: white}.header { padding: 20px; max-width: 600px background: black; color: white;}

You can leave off the semicolon on the last declaration in a ruleset. I’d warn that doing so manually will cause more trouble than it’s worth, and best left to minification tools.

Important: Avoiding Stray Characters

This is important in any language. Every character in code matters, so random other characters will almost certainly break things.

extra-chars.header { padding: 20px;}.header { { padding: 20px;}.header { padding: ~20px;}.header { /padding: 20px;}

Not Important: Line Breaks

A line break is treated like any other white space in CSS, so feel free to use them as needed, as long as it doesn’t break any other spacing rule like we talked about above.

line-breaks.bar { background-image: url(texture.png), url(tiger.jpg); }.button::after { content: ">";} .header { box-shadow: 0 0 5px rgba(0, 0, 0, 0.5), 20px 2px 5px -5px rgba(0, 0, 0, 0.5);}


All in all, CSS syntax isn’t so hard. Good luck!


CSS Basics: The Syntax That Matters & The Syntax That Doesn’t originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/css-basics-syntax-matters-syntax-doesnt/feed/ 6 265703