Home  >  Article  >  Web Front-end  >  CSS:你未必知道的@规则_html/css_WEB-ITnose

CSS:你未必知道的@规则_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:41:45916browse

at-rule是一个声明,为CSS提供执行或怎么表现的指令。每个声明以@开头,后紧跟一个可用的关键字,这个关键字充当一个标识符,用于表示CSS该做什么。这是一个通用的语法,尽管每个at-rule有其它语法变体。

常规规则

常规规则遵循下面的语法:

@[KEYWORD] (RULE);

@charset
这个规则定义了浏览器使用的字符集,如果样式表包含非ASCII characters (e.g:UTF-8)。注意,被放在HTTP头部的字符集将会覆盖@charset规则

@charset "UTF-8";

@import
这个规则指示请求样式表,在这一行,如果内容是正确的,就会引入一个外部的CSS文件。

@import 'global.css';

虽然流行的CSS预处理器都支持@import,但是应该指出的是,它们的工作原理不同于原生的CSS:预处理器会抓取CSS文件并将它们处理成一个CSS文件,对原生CSS,每一个@import都是一个独立的HTPP请求。
@namespace
对于将CSS应用在XML HTML(XHTML),这个规则是非常有用的,因为XHTML元素能在CSS中被作为一个选择器使用。

/* Namespace for XHTML */@namespace url(http://www.w3.org/1999/xhtml);/* Namespace for SVG embedded in XHTML */@namespace svg url(http://www.w3.org/2000/svg);

嵌套规则

嵌套规则包含了额外的子集声明,其中一些声明只能用于特定情况。

@[KEYWORD] {  /* Nested Statements */}

@document
这个规则为样式表指定了条件:只能应用于特定页面。举个粟子,我们提供一个URL,然后为这个特定的页面自定义样式,在其他页面中,这些样式会被忽略。

@document /* Rules for a specific page */ url(http://css-tricks.com/), /* Rules for pages with a URL that begin with... */ url-prefix(http://css-tricks.com/snippets/), /* Rules for any page hosted on a domain */ domain(css-tricks.com), /* Rules for all secure pages */ regexp("https:.*") {  /* Start styling */  body { font-family: Comic Sans; }}

@font-face
这个规则允许在web页面上加载自定义字体,对自定义字体有不同程度的支持,但是这个规则接受语句创建和提供这些字体。

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

@keyframes
在诸多CSS属性中,这个规则是关键帧  动画的基础,并允许我们标记动画开始和结束的标志。

@keyframes pulse {  0% { background-color: #001f3f; }  100% { background-color: #ff4136; }}

@media
这个规则包含条件声明,可用于为特定屏幕指定样式,这些声明可以包含屏幕大小,在适屏样式中会很有用.

/* iPhone in Portrait and Landscape */@media only screen   and (min-device-width: 320px)   and (max-device-width: 480px)  and (-webkit-min-device-pixel-ratio: 2) {    .module { width: 100%; }}

或者只在文档打印时运用样式

@media print {}

@page
这个规则为将要打印的单独页面定义样式。特别的是,它能为页面伪元素设置外边距::first、:left和:right

@page :first { margin: 1in; }

@supports
这个规则可测试浏览器知否支持某个特性/功能,如果满足条件,将会为这些元素应用特定样式。有点像Modernizr,但确实是CSS属性。

/* Check one supported condition */@supports (display: flex) {  .module { display: flex; }}/* Check multiple conditions */@supports (display: flex) and (-webkit-appearance: checkbox) {  .module { display: flex; }}

浏览器对@supports的支持情况:

Chrome Safari FireFox Opera IE Android IOS
28+ No 31+ 12.1+ No 4.4+ No

for more information of @supports,click here:@supports

总结

at-rule可以使CSS做一些疯狂有趣的事情。尽管文章中的示例很基础,但是可以看到,对于特定的条件,它们是如何使用样式的,从而创建匹配特定场景的用户体验和交互。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn