Skip to content
Advertisement

Issue when using title attribute on style element

Recently I came across a very weird issue. When you add more than one style element and if you add title attribute on style element with different value assigned in title. Only the first style element css gets applied.

 <!doctype html>
    <html>
      <head>
        <link rel="stylesheet" href="lib/style.css">
        <script src="lib/script.js"></script>

        <style title="Id-1">
          h1{color:red}
        </style>

        <style title="Id-2">
          h2{color:blue}
        </style>

      </head>

      <body>
        <h1>Hello Red Heading!</h1>
        <h2>Hello Blue Heading!</h2>
      </body>
    </html>

Now if you see in above simple HTML code. Following are possibilities of this code working-

  1. When no title attribute is added – It works.
  2. When title attribute is added with same value or no value – It works.
  3. When we assign different value in title attribute as shown in code only the first style element css gets applied i.e. h1 becomes red but no effect on h2.

On solution is to use data- to mark title as custom attribute or data attribute. I am more interested in knowing what is the reason behind this behavior.

To see it in action I have created a plunkr you can visit here

Advertisement

Answer

It’s because title on <style> is used to provide different subset of styles. Documentation

So basically going to View > Page Style you will see id-1 and id-2:

enter image description here


From documentation:

Any stylesheet in a document falls into one of the following categories:

Persistent (no rel="alternate", no title=""): always applies to the document. Preferred (no rel="alternate", with title="..." specified): applied by default, but disabled if an alternate stylesheet is selected. There can only be one preferred stylesheet, so providing stylesheets with different title attributes will cause some of them to be ignored.
Alternate (rel="alternate stylesheet", title="..." must be specified): disabled by default, can be selected.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement