在CSS中,“。”之间的区别是什么。和“#”当声明一组样式? [英] In CSS what is the difference between "." and "#" when declaring a set of styles?

查看:113
本文介绍了在CSS中,“。”之间的区别是什么。和“#”当声明一组样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#和。之间有什么区别。

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 selector ,用于定位具有唯一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 {} > 会使用属性 class =foo样式化所有元素(您可以将多个类分配给元素,只需用空格分隔它们,例如 class =foo bar

  • #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")

一般来说,你使用#作为你知道只会出现一次的样式,例如高级布局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中,“。”之间的区别是什么。和“#”当声明一组样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆