-
Notifications
You must be signed in to change notification settings - Fork 1
CSS Stylee
As with JavaScript, there are a couple of ways to include Cascading Style Sheets in your document.
The <link>
element was co-opted for importing stylesheets long before the <style>
element was specced, but it's a bit more verbose and limited to external stylesheets. Place this in the <head>
of your document:
<link rel="stylesheet" type="text/css" href="path/to/style.css">
NB: One thing that <link>
is good for is programmatically transforming CSS content, because it means that the transforming script won't have to parse out @import
directives and load styles separately. The best excuse that I've seen to use <link>
is prefixfree.
The <style>
element is much more concise and easier to remember than its <link>
equivalent. Here's its most basic form, which also belongs in the document's <head>
:
<style type="text/css">
body {
color: #fff;
background: #000;
}
</style>
You can load external stylesheets (a la <link>
, above) in CSS, like so:
<style type="text/css">
@import url(path/to/style.css);
</style>
Remember that style rule specificity is in part defined by its order in the stylesheet (i.e., the latter of two rules with the same specificity will always win). This makes overriding specific rules in imported stylesheets straightforward: Just declare your overrides after the @import
.
You can also add a "media" attribute to the <style>
tag, which tells the browser only to render those styles for the named media type. This is useful for specifying print-only (media="print"
) stylesheets, or for (conversely) limiting wilder styles to screen only (media="screen"
).
Remember that if you don't include a "media" attribute, the styles will be applied to all media. If there's any chance that people will be printing your page, it's best to set your stylesheet's media to "screen" first, then specify your print-specific stylesheet separately.
There's another, more "modern" way to limit CSS rules to specific media (which may be appropriate if there are only a handful of such rules, and a separate stylesheet would be overkill). In CSS, you can wrap one or more style rules in an @media type { ... }
block, like so:
body {
font-family: Helvetica, sans-serif;
}
@media print {
body {
font-family: "Hoefler Text", serif;
}
}
In this case, the page will be printed with a different font family than the one shown on screen.