CSS Introduction | Advanced CSS | @-Rules
@-Rules
CSS can use several rules defined by the W3C. The most commonly used representative rules are as follows.
- @import
- @font-face
- @media
@import Rule
The @import rule imports style rules from another style sheet. Except for the @charset rule, which specifies the character encoding used by the style sheet, this rule must be written before every other rule.
Usually, an HTML document adds several style sheets by using multiple <link> tags as shown below.
<head>
<title>@import rule</title>
<link rel="stylesheet" href="firstStyleSheet.css">
<link rel="stylesheet" href="secondStyleSheet.css">
...
<link rel="stylesheet" href="hundredStyleSheet.css">
</head>
However, as the number of CSS files added this way increases, the load on the web server also increases. Therefore, a common approach is to add only a certain number of CSS files to the HTML document, and then use the @import rule inside those CSS files to add additional CSS files.
<head>
<title>@import rule</title>
<link rel="stylesheet" href="firstStyleSheet.css">
<link rel="stylesheet" href="secondStyleSheet.css">
</head>
firstStyleSheet.css
@import url("thirdStyleSheet.css");
@import "fourthStyleSheet.css";
...
Even when using the @import rule, the load on the web server still grows if the number of CSS files keeps increasing. Therefore, you need a way to distribute and include the CSS files appropriately to reduce server load.
With the @import rule, you can selectively load only the CSS files needed for specific media query conditions.
The following example loads firstStyleSheet.css when printing, and loads secondStyleSheet.css when the screen is set to landscape orientation.
<head>
<title>@import rule</title>
@import url("firstStyleSheet.css") print;
@import "secondStyleSheet.css" screen and (orientation:landscape);
</head>
@font-face Rule
The @font-face rule is used to define web fonts. A web font allows a web browser to use a font that is not installed on the user’s computer.
First, upload the web font to the server. Then define and add the web font in a CSS file by using the @font-face rule. After that, every web browser that accesses the page automatically downloads the web font from the server and displays the text with that font.
<style>
@font-face {
font-family: "myWebFont";
src: local("NanumGothic"), url("NanumGothic.eot"), url("NanumGothic.ttf"), url("NanumGothic.woff");
}
* { font-family: "myWebFont"; }
</style>
@media Rule
CSS2 supports customized style sheets for different media types through the @media rule.
The following example applies different styles when the HTML document is displayed on a screen and when it is printed.
<style>
body { background-color: darkorange; }
@media screen {
body { background-color: black; color: white; }
}
@media print {
body { background-color: white; color: black; }
}
</style>