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

查看:17
本文介绍了在 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 选择器,用于以具有唯一 id 的 single 特定元素为目标,但是 .是一个类选择器,用于定位多个元素一个特定的班级.换句话说:

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 {} 将为使用 id="foo"
  • 属性声明的 single 元素设置样式
  • .foo {} 将使用属性 class="foo" 设置 all 元素的样式(您可以将多个类分配给一个元素同样,只需用空格分隔它们,例如 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 选择器被认为比类选择器更具体.这意味着在元素上的样式 conflict 中,定义的样式更具体选择器将覆盖不太具体的选择器.例如,给定 <div id="sidebar" class="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

请参阅 Selectutorial 了解更多关于 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.

看起来 Selectutorial 可能已经去了天空中的大网站,所以试试这个 存档链接.

Looks like Selectutorial might have gone to the big website in the sky, so try this archive link instead.

这篇关于在 CSS 中,“."之间有什么区别?和“#"声明一组样式时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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