Difference between [ID="MAIN"] and #MAIN

Asked

Viewed 120 times

2

Guys, can anyone tell me the difference between:

  • [ID=""] and #
  • [CLASS=""] and .

What difference do they make, code get bigger? Uglier?

2 answers

3

They look alike. The [] is the attribute selector, and CSS selects elements that have exactly this attribute.

Notice that when you use the method [class="foo bar"] it will only work on elements that have both the classes. Whereas div.foo acts on all Ivs that have this class.

The technique [] is useful for other attributes than id or class, because these have their own selectors and are simpler to use or match.

Example:

div[class="um"] {
    background-color: #ccf;
}
div.um{
    border:2px solid red;
}
<div class="um">1</div>
<div class="dois">2</div>
<div class="um dois">1 2</div>

(jsFiddle: http://jsfiddle.net/1rcxfrxz/)

When you use div.um it acts on two elements, when you use div[class="um"] it only acts on one element.

  • In this case, it can use the selector .foo.bar, which generates the same effect as [class="foo bar"].

  • 1

    @Wallacemaxters only one note .foo.bar is not the same thing as [class="foo bar"], with = the value that that be exact of the way it was written, already with ., there may be numerous spaces and variations of position that yet elements are found.

2

# (Sharp)

Already a character for representation of element ID by default in css.

[ID="MAIN"] (Attribute Selector)

It means that you are using a CSS3 selector type, where you can "pick up" an element by attribute (Attribute Selector). In this case, you’re picking up by the id (thing that sharp # already makes)

The suggestion, in this case, is to use #, to keep your code standardized :)

Complex Expressions for Capturing Elements by Attributes

The attribute selector is more complex than that. It can only take an element if we define the part of the name of an attribute.

Example

[class=^"box-"]{
 color:#f00;
}

<div class='box-1'></div>
<div class='box-2'></div>
<div class='box-3'></div>


[class*="test"] {
    background: #ffff00;
}

<div class="first_test">The first div element.</div>
<div class="second">The second div element.</div>
<div class="test">The third div element.</div>
<p class="test">This is some text in a paragraph.</p>
  • Puts, the question has changed :\

Browser other questions tagged

You are not signed in. Login or sign up in order to post.