Kayla Scott
Kayla Scott

Reputation: 23

Internal style does not work in this HTML code?

<html>
<head>
<style>
#1fineday {
    color:yellow;
}
</style>
</head>
<body>
<h1>Welcome</h1>
<div class="intro">
  <p id="1fineday">Hello World</p> 
</div>
</body>
</html>

Shouldn't "Hello World" be yellow? I don't understand why internal CSS styling I wrote doesn't apply. The ID is 1fineday. I must be overlooking something.

Upvotes: 2

Views: 63

Answers (2)

Ray Toal
Ray Toal

Reputation: 88378

There's a technicality in the way that you write CSS selectors using the # character. You can always write the selector to use the attribute selector

[id="1fineday"] {
    color:yellow;
}

and you'll see yellow text.

You can't write #1fineday in the selector, because, as the official CSS Selector Specification says:

An ID-typed attribute of a document language allows authors to assign an identifier to one element instance in the document tree. An ID selector contains a "number sign" (U+0023, #) immediately followed by the ID value, which must be an CSS identifiers. An ID selector represents an element instance that has an identifier that matches the identifier in the ID selector.

The syntax for CSS identifiers is given in the official spec with these words:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".

Therefore if you still want to use the #, you'll have to use the escape code for the number 1:

#\31 fineday {
    color:yellow;
}

Thanks to misorude in the comments for pointing the latter trick out, and noting that the specificity rules are different between the id and attribute selectors.

Upvotes: 1

Tu Nguyen
Tu Nguyen

Reputation: 10179

Because of naming convention, your id cannot start with a number

<html>

<head>
  <style>
    #fineday {
      color: yellow;
    }
  </style>
</head>

<body>
  <h1>Welcome</h1>
  <div class="intro">
    <p id="fineday">Hello World</p>
  </div>
</body>

</html>

Remove the number 1 and it will work

For reference:

W3Schools: https://www.w3schools.com/css/css_syntax.asp

CSS-Tricks: https://css-tricks.com/ids-cannot-start-with-a-number/

Upvotes: 2

Related Questions