问题描述
#和。之间有什么区别。
What is the difference between "#" and "." when declaring a set of styles for an element and what are the semantics that come into play when deciding which one to use?
推荐答案
当声明一个元素的样式集时,什么是在决定使用哪个语义时出现的语义?是的,它们是不同的...
#
是,用于定位具有唯一ID的单个特定元素,但是。是用于定位多个元素的与特定类。换句话说:
Yes, they are different...
#
is an id selector, used to target a single specific element with a unique id, but . is a class selector used to target multiple elements with a particular class. To put it another way:
-
#foo {}
>.foo {}
将会用属性class =foo
样式化所有元素(您可以将多个类分配给元素,只需用空格分隔它们,例如class =foo bar
)
#foo {}
will style the single element declared with an attributeid="foo"
.foo {}
will style all elements with an attributeclass="foo"
(you can have multiple classes assigned to an element too, just separate them with spaces, e.g.class="foo bar"
)
一般来说,你使用#来定义你知道只会出现一次的东西,例如高级布局div这样的边栏,横幅区域
Generally speaking, you use # for styling something you know is only going to appear once, for example, things like high level layout divs such sidebars, banner areas etc.
类在重复样式时使用,例如假设你头部有一个特殊形式的错误消息头,你可以创建一个风格 h1.error {}
,它只适用于< h1 class =error>
Classes are used where the style is repeated, e.g. say you head a special form of header for error messages, you could create a style h1.error {}
which would only apply to <h1 class="error">
在其特殊性 - 一个id选择器被认为比类选择器更具体。这意味着,对于元素定义的样式,,特定选择器将覆盖较少的特定选择器。例如,< div id =sidebarclass =box>
#sidebar
对 .box
Another aspect where selectors differ is in their specificity - an id selector is deemed to be more specific than class selector. This means that where styles conflict on an element, the ones defined with the more specific selector will override less specific selectors. For example, given <div id="sidebar" class="box">
any rules for #sidebar
with override conflicting rules for .box
请参见,了解有关CSS选择器的更多强大的引导 - 它们非常强大,如果你的概念只是#用于DIV,你会很好地了解如何更有效地使用CSS。
See Selectutorial for more great primers on CSS selectors - they are incredibly powerful, and if your conception is simply that "# is used for DIVs" you'd do well to read up on exactly how to use CSS more effectively.
这篇关于在CSS中,“。”之间的区别是什么。和“#”当声明一组样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!