Danny_Student
Danny_Student

Reputation: 153

Why must I be precise when selecting html elements?

I'm doing a tutorial which will result in a fancy html5/css3/js based calculator. Something that never happened to me before - I've tried to style the operator elements differently like that they can be easily distinguished from other keys like 0-9.

I've typed in my CSS .keys .operator and added a different background property. However, it didn't work.

Then I've tried to be more specific like .keys span.operator.

This worked. However, it have left me with question marks.

My question:

Why in this case I need to be so specific or else CSS doesn't swallow the background property?

Why I can't just type .operator class alone?

I thought that by typing .keys .operator, I select every html element with a class of .operator within any element that has a class of .keys.

That sounds logical to me but it didn't work.

If I would go with the train of thought imposed to me by force by CSS then theoretically I would need to be even more precise and write div.keys span.operator but in the tutorial it's not needed.

Can someone explain to me why?

Here's the code that I'm working on:

http://codepen.io/anon/pen/qgjyp

Upvotes: 0

Views: 130

Answers (2)

skovy
skovy

Reputation: 5650

You are using more precision. The more 'precise' your CSS selector is, the more precedence it has over other CSS that is selecting the same element but with less precision.

You most likely have CSS below it that is overriding the CSS you provided or CSS that is more precise somewhere in your CSS file.

For example, span is less specific than span.MyClass so span.MyClass will take precedence over span. Any style with the !important attribute is an automatic win over anything, but should rarely be used.

Look over your CSS document or inspect it in the browser and see what classes are affecting that element.

Check out this link: Specifics on CSS Specificity

Upvotes: 2

tjons
tjons

Reputation: 4769

I just took a look, and if I remove the span in front of your .operator, it is fine for me. It might be an issue with your browser. I am using Chrome Canary. Here is a link to the pen: http://codepen.io/anon/pen/eGCfn

Upvotes: 0

Related Questions