CSS - @ Rules

-

@charset

The @charset rule in CSS specifies the character encoding of an external stylesheet. It helps the browser interpret the characters correctly, especially when using non-ASCII characters or special symbols in your CSS code.

The @charset rule tells the browser what character encoding to use when reading the stylesheet. This makes sure that the characters in your CSS file are displayed correctly, avoiding issues related to character encoding mismatches.

The syntax of the @charset rule is simple. It should be placed at the very top of your CSS file, before any other rules or comments. The @charset rule is followed by the character encoding in quotes.

Example: Simple Syntax of the @charset Rule

@charset "UTF-8";

The character encoding is set to UTF-8, which is a widely used character encoding that supports a wide range of characters from different languages. UTF-8 is a good choice for most web projects as it covers many characters and works with many browsers.

The @charset rule must be the first thing in your CSS file, with no other characters or whitespace before it. Also, the @charset rule should only be used once per stylesheet.

Example: Using the @charset Rule in Your CSS File

@charset "UTF-8";

body {
  font-family: Arial, sans-serif;
}

h1 {
  color: #FF0000;
}

By using the @charset rule and specifying the right character encoding, you can make sure that your CSS file is interpreted correctly by the browser, displaying the characters as intended and avoiding any encoding-related issues.

@import

The @import rule in CSS includes styles from one stylesheet into another. It lets you split your CSS code into multiple files, making it easier to organize and maintain your styles.

The main purpose of the @import rule is to help you keep your CSS code modular and separate different parts of your styles into individual files. This can be useful for large projects where you want to break down your styles into smaller, more manageable parts.

The syntax of the @import rule is straightforward. It is placed at the top of your CSS file, and it is followed by the URL of the stylesheet you want to import, wrapped in quotes or url().

Example: Importing Stylesheets

@import "styles.css";
@import url("more-styles.css");

In the first example, the @import rule includes the "styles.css" file into the current stylesheet. The second example shows how to use the url() function to import the "more-styles.css" file.

You can import multiple stylesheets by using multiple @import rules:

Example: Importing Multiple Stylesheets

@import "reset.css";
@import "typography.css";
@import "layout.css";

In this example, three different stylesheets are imported: "reset.css", "typography.css", and "layout.css". The order of the @import rules is important, as the styles from the imported stylesheets will be applied in the order they are listed.

It's important to note that the @import rule should be placed at the top of your CSS file, before any other rules or selectors. Also, keep in mind that using @import can impact the performance of your website, as it requires additional HTTP requests to load the imported stylesheets.

An alternative to using the @import rule is to use the <link> tag in your HTML file to include external stylesheets:

Example: Using Link Tag in HTML

<link rel="stylesheet" href="styles.css">

Using the <link> tag has some advantages over @import:

Advantage Description
Parallel loading The stylesheets are loaded in parallel with the HTML document, which can improve the loading speed of your website.
Avoid unstyled content flashing The stylesheets are loaded and applied before the page renders, avoiding any unstyled content flashing.

However, the @import rule can still be useful in certain situations, such as when you want to conditionally load stylesheets based on media queries or when you're working with CSS preprocessors like Sass or Less.

@media

The @media rule in CSS applies different styles based on the device or media where the web page is displayed. It lets you create responsive designs that adapt to different screen sizes, device capabilities, and media types.

The @media rule gives you control over how your web page looks and behaves on various devices and media conditions. By using media queries, you can specify different CSS styles that will be applied when certain conditions are met, such as the screen width, height, orientation, or device type.

The syntax of the @media rule consists of the @media keyword followed by a media query enclosed in parentheses. Inside the parentheses, you define the media type and any additional media features or conditions. The CSS rules that should be applied when the media query matches are placed inside curly braces.

Example: Basic @media syntax

@media (media-feature: value) {
  /* CSS rules */
}
/* Default styles */
body {
  font-size: 16px;
}

/* Styles for screens with a maximum width of 600px */
@media (max-width: 600px) {
  body {
    font-size: 14px;
  }
}

/* Styles for screens with a minimum width of 1200px */
@media (min-width: 1200px) {
  body {
    font-size: 18px;
  }
}

In this example, the default font size for the <body> element is set to 16px. However, when the screen width is 600px or less, the font size is reduced to 14px. On the other hand, when the screen width is 1200px or more, the font size is increased to 18px.

You can use various media features in your media queries to target specific conditions. Some common media features include:

Media Feature Description
width, height Specify the width or height of the viewport.
min-width, max-width Set a minimum or maximum width for the viewport.
orientation Target either landscape or portrait orientation.
device-width, device-height Specify the width or height of the device screen.

By combining these media features and defining appropriate styles, you can create responsive designs that adapt to different screen sizes and devices.

Media queries are a key component of responsive web design. They let you provide optimal viewing experiences across a wide range of devices, from smartphones and tablets to desktop screens. By using media queries, you can adjust the layout, font sizes, images, and other design elements to suit the specific characteristics of each device.

Example: Responsive design with @media

/* Default styles */
.container {
  width: 100%;
  padding: 20px;
}

/* Styles for screens with a minimum width of 768px (tablets) */
@media (min-width: 768px) {
  .container {
    width: 750px;
    margin: 0 auto;
  }
}

/* Styles for screens with a minimum width of 1200px (desktops) */
@media (min-width: 1200px) {
  .container {
    width: 1170px;
  }
}

In this example, the .container class has a default width of 100% and padding of 20px. When the screen width is 768px or more (targeting tablets), the container width is set to 750px and centered using margin: 0 auto. For screens with a width of 1200px or more (targeting desktops), the container width is increased to 1170px.

By using media queries and adjusting the styles based on different screen sizes, you can create a responsive layout that adapts to different devices, providing an optimal user experience across a wide range of screens.

The @media rule is a powerful tool in CSS that enables you to create responsive and adaptive designs. By leveraging media queries and defining appropriate styles for different media conditions, you can enhance the usability and visual appeal of your web pages across various devices and screen sizes.

@font-face

The @font-face rule in CSS lets you define and use custom fonts on your web pages. It allows you to embed fonts that may not be installed on the user's device, giving you more control over the typography and design of your website.

The @font-face rule provides a way to use fonts beyond the standard web-safe fonts. By using custom fonts, you can improve the visual appeal and branding of your website, making it stand out.

The syntax of the @font-face rule has the @font-face keyword followed by a block of font properties in curly braces. Inside the block, you specify the font family name, the source of the font file, and optional font properties such as style, weight, and format.

Example: CustomFont Definition

@font-face {
  font-family: 'CustomFont';
  src: url('custom-font.woff2') format('woff2'),
       url('custom-font.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

The src property specifies the URLs of the font files in different formats (WOFF2 and WOFF) along with their format hints. The font-weight and font-style properties are set to normal.

Once you have defined your custom font using the @font-face rule, you can use it in your CSS styles by referencing the font family name.

Example: Using CustomFont

@font-face {
  font-family: 'CustomFont';
  src: url('custom-font.woff2') format('woff2'),
       url('custom-font.woff') format('woff');
}

body {
  font-family: 'CustomFont', Arial, sans-serif;
}

h1, h2, h3 {
  font-family: 'CustomFont', Georgia, serif;
}

In this example, the custom font "CustomFont" is applied to the <body> element as the main font, with Arial and sans-serif as fallback fonts. The headings (<h1>, <h2>, <h3>) also use the custom font, with Georgia and serif as fallback fonts.

When using custom fonts with the @font-face rule, keep these best practices in mind:

Best Practice Description
Use web-friendly font formats Use font formats that are widely supported by browsers, such as WOFF2, WOFF, or TTF. WOFF2 is recommended for its better compression and faster loading times.
Provide fallback fonts Always specify fallback fonts in case the custom font fails to load or is not supported by the user's browser. Use a combination of generic font families (e.g., sans-serif, serif) and specific font names.
Optimize font files Compress your font files to reduce their file size and improve loading performance. Tools like FontSquirrel or FontForge can help optimize fonts for the web.
Limit the number of custom fonts Using too many custom fonts can impact page load times and performance. Limit the number of custom fonts and use them strategically for important elements like headings or branding.
Consider web font services If you don't want to host font files yourself, you can use web font services like Google Fonts or Adobe Typekit. These services provide a wide range of fonts and handle the hosting and optimization for you.

@keyframes

The @keyframes rule in CSS lets you define and control the steps of an animation. It specifies the styles and properties that an element should have at different points during the animation sequence. By using @keyframes, you can create dynamic and engaging animations on your web pages.

The main purpose of the @keyframes rule is to give you control over the animation process. You can define the start and end states of the animation, and intermediate points, called keyframes, where specific styles are applied. This allows you to create smooth transitions and complex animation effects.

The syntax of the @keyframes rule consists of the @keyframes keyword followed by a name for the animation. Inside the rule, you define the keyframes using percentages or the keywords "from" and "to". Each keyframe specifies the styles that should be applied at that point in the animation.

Example: Defining Keyframes

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

The animation named "fadeIn" is defined. It has two keyframes: "from" representing the start of the animation (0% progress) and "to" representing the end of the animation (100% progress). The "from" keyframe sets the opacity to 0, making the element fully transparent, while the "to" keyframe sets the opacity to 1, making the element fully opaque.

You can also use percentages to define intermediate keyframes:

Example: Intermediate Keyframes

@keyframes bounce {
  0% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-20px);
  }
  100% {
    transform: translateY(0);
  }
}

The "bounce" animation has three keyframes defined at 0%, 50%, and 100%. At the beginning (0%), the element is at its original position. At the midpoint (50%), the element is translated upwards by 20 pixels using the transform property. At the end (100%), the element returns to its original position.

To apply the defined animation to an element, you use the animation property or its individual sub-properties:

Example: Applying Animation

.element {
  animation-name: fadeIn;
  animation-duration: 1s;
  animation-timing-function: ease;
  animation-delay: 0.5s;
  animation-iteration-count: infinite;
}

The "fadeIn" animation is applied to the element with the class ".element". The animation-duration property sets the duration of the animation to 1 second, the animation-timing-function property defines the easing function as "ease", the animation-delay property adds a delay of 0.5 seconds before the animation starts, and the animation-iteration-count property makes the animation repeat indefinitely.

You can create more complex animations by combining multiple keyframes and properties:

Example: Complex Animation

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.2);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.button {
  animation: pulse 2s ease-in-out infinite;
}

The "pulse" animation scales the element up and down while also changing its opacity. The animation is applied to an element with the class ".button" using the shorthand animation property, specifying the animation name, duration, timing function, and iteration count.

The @keyframes rule provides a way to create animations in CSS. By defining keyframes and applying them to elements, you can add visual interest, guide user attention, and improve the overall user experience on your web pages. Experiment with different properties, timing functions, and keyframe percentages to create unique and captivating animations.

@supports

The @supports rule in CSS is a feature query that lets you apply styles based on whether a browser supports a CSS property or value. It detects browser support and conditionally applies styles, enabling progressive enhancement and graceful degradation in your web designs.

The main purpose of @supports is to apply your styles only when the browser supports the specified CSS feature. This is useful when working with newer CSS properties or values that may not be supported by all browsers. By using @supports, you can provide fallback styles for browsers that don't support the feature while still using the latest CSS capabilities in modern browsers.

The syntax of @supports consists of the @supports keyword followed by a CSS declaration or a logical combination of declarations in parentheses. Inside the rule block, you define the styles that should be applied when the condition is met.

Example: Simple Syntax of the @supports Rule

@supports (property: value) {
  /* CSS rules */
}

Example: Using @supports for Feature Detection

@supports (display: grid) {
  .container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 20px;
  }
}

@supports not (display: grid) {
  .container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }
}

In this example, @supports checks if the browser supports display: grid. If it does, the styles inside the first @supports block are applied, setting the .container element to use a grid layout with three equal-width columns and a gap of 20 pixels between them.

If the browser doesn't support display: grid, the styles inside the second @supports block are applied instead. In this case, the .container element uses a flex layout with wrapping and space between the items.

You can also use logical operators like and, or, and not to combine multiple conditions in @supports:

Example: Combining Conditions with Logical Operators

@supports (display: grid) and (grid-template-columns: repeat(3, 1fr)) {
  .container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 20px;
  }
}

In this example, the styles are applied only if the browser supports both display: grid and grid-template-columns with the repeat() function and fr unit.

@supports is a tool for progressive enhancement in web development. It lets you gradually enhance the user experience by providing advanced styles and layouts for modern browsers while still ensuring a functional and accessible experience for older browsers.

By using @supports, you can write CSS code that adapts to the capabilities of different browsers, gracefully degrading when necessary and progressively enhancing the design when possible. This helps you create web pages that are accessible and usable across a wide range of devices and browsers.

Remember to always provide fallback styles for browsers that don't support the features you're using. This ensures that your content remains accessible and readable, even if some advanced styling is not applied.

@namespace

The @namespace rule in CSS defines namespaces for XML documents. Its purpose is to avoid conflicts between element names when working with multiple XML vocabularies in the same document.

In XML, namespaces identify elements and attributes from different vocabularies. By using namespaces, you can use the same element or attribute names in your document without causing naming conflicts.

The syntax of the @namespace rule is:

Example: Syntax of @namespace rule

@namespace prefix url(namespace-url);

The prefix is an optional prefix that you can use to reference the namespace in your CSS selectors. The namespace-url is the URL that identifies the namespace.

Example: Define a namespace using the @namespace rule

@namespace svg url(http://www.w3.org/2000/svg);

In this example, the namespace with the URL "http://www.w3.org/2000/svg" is defined and associated with the prefix "svg". This namespace is commonly used for SVG (Scalable Vector Graphics) elements.

Once you have defined a namespace, you can use the prefix in your CSS selectors to target elements within that namespace:

Example: Use prefix in CSS selectors

@namespace svg url(http://www.w3.org/2000/svg);

svg|circle {
  fill: red;
}

svg|rect {
  stroke: blue;
  stroke-width: 2px;
}

In this example, the "svg" prefix is used in the selectors svg|circle and svg|rect to target the <circle> and <rect> elements within the SVG namespace. The styles defined will only apply to elements in that specific namespace.

You can also define multiple namespaces in your CSS:

Example: Define multiple namespaces

@namespace svg url(http://www.w3.org/2000/svg);
@namespace xlink url(http://www.w3.org/1999/xlink);

svg|a[xlink|href] {
  fill: green;
}

Here, two namespaces are defined: "svg" for SVG elements and "xlink" for the XLINK attributes. The selector svg|a[xlink|href] targets <a> elements within the SVG namespace that have an xlink:href attribute.

By using the @namespace rule and prefixes in your selectors, you can apply styles to elements within a particular namespace, avoiding conflicts with elements that have the same name but belong to different vocabularies.

The @namespace rule is primarily used when working with XML documents that use multiple namespaces. In HTML, the use of namespaces is less common, and the @namespace rule is not as frequently used.

When working with XML documents that require namespaces, the @namespace rule in CSS lets you define and reference those namespaces, allowing you to style elements accurately and avoid naming conflicts.

@page

The @page rule in CSS defines styles for printed pages or documents for paging media, such as PDFs. It controls the layout, margins, and other properties of the printed page.

The @page rule gives you control over how your web content looks when printed. By using @page, you can define different styles for the printed version of your web page, making it more suitable for paper or other paging media.

The syntax of the @page rule consists of the @page keyword followed by an optional page selector and a block of CSS declarations in curly braces.

Example: Basic Syntax

@page {
  /* CSS declarations */
}

Inside the @page rule, you can use properties to control the layout and appearance of the printed page.

Property Description
size Specifies the size of the page box, such as "A4", "letter", or a custom size.
margin Sets the margins of the page box.
padding Sets the padding of the page box.
page-break-before, page-break-after Controls page breaks before or after an element.
orphans, widows Defines the minimum number of lines that must be left at the bottom or top of a page.

Example: Styles for Printed Pages

@page {
  size: A4;
  margin: 2cm;
}

@media print {
  body {
    font-size: 12pt;
  }

  h1 {
    page-break-before: always;
  }

  table {
    page-break-inside: avoid;
  }
}

You can also control page breaks and margins for specific elements using the @page rule with CSS pseudo-classes:

Example: Pseudo-Classes

@page :first {
  margin-top: 4cm;
}

@page :left {
  margin-left: 3cm;
  margin-right: 2cm;
}

@page :right {
  margin-left: 2cm;
  margin-right: 3cm;
}

h2 {
  page-break-after: avoid;
}

By using the @page rule and its properties, you can adjust the appearance of your web content when printed or shown in paging media. This includes controlling page sizes, margins, page breaks, and other aspects of the printed layout.

Test your styles with different print settings and devices to get the desired results. The @page rule gives you the power to create print-friendly versions of your web pages, improving the user experience when printing content.