我以前也查过这方面的资料,今天看到这段感觉写的很明白:
#
is an id selector, used to target a single specific element with a unique id, but . is a class selectorused to target multiple elements with a particular class. To put it another way:
#foo {}
will style the single element declared with an attribute id="foo"
.foo {}
will style all elements with an attribute class="foo"
(you can have multiple classes assigned to an element too, just separate them with spaces, e.g. class="foo bar"
)#用于id, id定义多个元件(element); . 用于 class, class 用于多个元件的共同属性。
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.
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">
#用于只显示一次,比如,sidebars、banner区
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
id 优先于class