Link to home
Start Free TrialLog in
Avatar of elepil
elepil

asked on

CSS3 problem

In my HTML file, I am using CSS3's attribute selectors:

p[name^="my"] {
    font-size: 30px;
    color: aqua;
}

p[name$="my"] {
    font-size: 40px;
    color: brown;
}

p[name*="my"] {
    font-size: 50px;
    color: darkorange;
}

They are used in my HTML file as:

<p name="mytext">This should be 30px and color aqua</p>
<p name="textmy">This should be 40px and color brown</p>
<p name="textmytext">This should be 50px and color darkorange</p>

But when I render my HTML document, they all seem to be 50px and darkorange, as if the last attribute selector overrides everything prior.

Is this the expected behavior??? Because my book does not say so.

Thanks.
Avatar of Alexandre Simões
Alexandre Simões
Flag of Switzerland image

Yep, this is the expected behavior.
The last selector always match on top of the 2 before and as it comes after it just overrides it.

This is a common behavior in CSS (nothing CSS3 specific) and it applies to all selectors.
It is in fact the behavior that makes it possible, for instance, to override styles defined in a file with styles defined in another file.

So your solution here is to move the last selector before the other 2:
p[name*="my"] {
    font-size: 50px;
    color: darkorange;
}
p[name^="my"] {
    font-size: 30px;
    color: aqua;
}
p[name$="my"] {
    font-size: 40px;
    color: brown;
}

Open in new window


Like this the first selector will only be the final one if "my" is somewhere in the middle which I think it's your goal.
Avatar of elepil
elepil

ASKER

Alex, thank you for your response. Your recommended solution clearly works, but your explanation totally confuses me.

You said, "The last selector always match on top of the 2 before and as it comes after it just overrides it.", and that makes absolutely no sense to me. Can you please elaborate on this?

I'm making this post not only to obtain a solution from more experienced CSS users like you, but I would also like to understand the thinking behind so I don't commit the same error in the future, so please bear with me.
ASKER CERTIFIED SOLUTION
Avatar of Alexandre Simões
Alexandre Simões
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of elepil

ASKER

Thanks, AlexCode, it is crystal clear to me now! After your second clearer explanation, even your first explanation now makes sense to me. :)