0

Sorry for such a basic question. when writing different div elements to later ID and style in css, can I name them whatever I want?

<div id="middle"></div>

<div id="yellow box"></div>

<div id="my dog"></div>

<div id="the green hornet"></div>

thanks. p

scaisEdge
  • 124,973
  • 10
  • 73
  • 87

1 Answers1

0

Yes, you can use whatever ID you can come up with.

In JavaScript

This used to be a limitation when you wanted to access elements via their ID in some old browsers (Internet Explorer 5-6), that added functionality to access elements with an ID, for example:

document.all.middle // worked
document.all.yellow box // did not work (of course)

This behavior was only supported by Internet explorer however, and should not be used. Use something like this to access an element in JavaScript instead:

document.getElementById('my dog').textContent = 'Hello';
document.getElementById('the green hornet') = 'World';

In CSS

You need to escape spaces in CSS:

div#my weird spaced id {
  /* does not work */
}

div#my\ weird\ spaced\ id {
  /* works */
}

This does not work for classes however:

<div class="a b c">color me!</div>

div.a\ b\ c { color: red } /* does not work */

For classes, a b c means "class a and class b and class c". If you really really have to use them this way, you can style them via dot notation:

`div.a.b.c { color: red } /* works */

The best practice is to name them dash-separated, e.g. my-fancy-class, main-nav-header, etc.
If you prefer camelCase or underscore_notation, you can use them too, but dash-seprarated is more widespread.

Leon Adler
  • 2,330
  • 1
  • 21
  • 38