如果我想在我的网站上限制字体系列的使用,比如2到3种不同的字体(例如Times, Arial等)。有没有一种方法可以组织我的CSS让我有像
这样的东西 fontType1 is font-family: "Times New Roman", Times, serif;
fontType2 is font-family: Arial, sans-serif
然后对于我在CSS中样式化的每个UI元素,从可用的字体类型中选择,即fontType1, fontType2。对于我的颜色选择集也是如此。
如果我改变fontttype1的字体族,我希望它贯穿整个站点/样式表。我不想去修改每一个css声明。如果我想改变一个网站的"深色",我希望它能贯穿整个网站;我不想每次都去修改它
如果我正确理解你的问题,最好的方法(不使用预处理器)是:
h1,h2,h3,h4,h5,h6,
.button, .promo{ /* Your list of selectors that need to use this font stack */
font-family:one;
}
p,ul,
.small-print,.error{ /* Your list of selectors that need to use this font stack */
font-family:two;
}
#nav,#footer{ /* Your list of selectors that need to use this font stack */
font-family:three;
}
这不依赖于JS,它不会膨胀你的HTML,最好的事情是你可以一次更新所有的实例:)
这样你只需要在列表中添加新的选择器,而不必重新定义你的family。把它放在"共享"部分。我写在这里:http://coding.smashingmagazine.com/2011/08/26/writing-css-for-others/(做一个查找"共享")。
H没有办法直接使用CSS实现这一点,但这是Sass、LESS和Compass等库的主要功能之一。LESS可以通过服务器端或客户端Javascript编译,而Sass是用Ruby编译的。Compass是一个库,允许在Rails或Ruby web应用程序的上下文之外编译Sass。
下面是你可以用Sass做的一个例子:
$color: #4D926F;
#header {
color: $color;
}
h2 {
color: $color;
}
和它被编译成的CSS:
#header {
color: #4D926F;
}
h2 {
color: #4D926F;
}
除了变量,如上所示,你还可以得到mixins(基本上是函数)和嵌套选择器。
设置如下:
.font-type1 { font-family: font1, font2, font3; }
.font-type2 { font-family: font4, font5, font6; }
.font-type3 { font-family: font7, font8, font9; }
并将它们设置在<body>
元素上。
如果你想用JavaScript动态修改它:
HTML
<a class=changefont data-font="font-type1" href=#>Font 1</a>
<a class=changefont data-font="font-type2" href=#>Font 2</a>
<a class=changefont data-font="font-type3" href=#>Font 3</a>
JavaScript 和javascript(我使用jQuery的简单性,也可以用js单独完成)
$('.changefont').click(function() { $('body').removeClass().addClass($(this).data('font')); });
这里有一个例子!
通过更改更高级的祖先类,可以在整个文档上创建一个漂亮的级联(Cascading Style Sheet)。
另一种方法是为UI元素添加一些类。
CSS:.fontType1 {font-family: "Times New Roman", Times, serif}
.fontType2 {font-family: Arial, sans-serif}
HTML: <h1 class="fontType1">Header 1</h1>
<p class="someOtherCssClass fontType2">paragraph text goes here</p>