Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it wrong to use CSS in this way?

Lately I'm using a CSS structure that makes HTML much cleaner but I don't know if there's something wrong with this.

Instead of using:

.top { //properties }

.top-wrapper { //properties }

.top-logo { //properties }

And for HTML:

<div class="top">
    <div class="top-wrapper">
        <a href="" class="top-logo">Logo</a>
    </div>
</div>

I'm actually coding like this:

.top { //properties }

.top .wrapper { //properties }

.top .wrapper .logo { //properties }

And for HTML:

<div class="top">
    <div class="wrapper">
        <a href="" class="logo">Logo</a>
    </div>
</div>

Is it wrong to do this?

like image 919
Cainã Avatar asked Nov 30 '12 13:11

Cainã


3 Answers

It is not wrong, but the more selectors you have, the higher the resulting specifity of your style. For more information about specifity see http://www.w3.org/TR/CSS21/cascade.html#specificity.

Imagine your example

.top .wrapper .logo { font-size: 10px; }

followed by this:

.logo { font-size: 20px; }

The <a class="logo"> will have a font-size of 10px, even though you specified it to be 20px for the second declaration.

like image 108
kontur Avatar answered Sep 24 '22 20:09

kontur


It isn't necessarily "wrong" to do this, it works and if you find it easy to use I'd say go for it!

However - there are some drawbacks to this approach, for example your CSS file will end up larger, which will mean longer download times for anybody viewing the website (granted this effect may be negligible)

There's also the issue that, if you want to re-use the styles of top-wrapper on another element, you have to place that element inside a div with a top class, this ends up cluttering your HTML.

(For more information on the above point see OOCSS)

At the end of the day there are benefits and drawbacks to any approach, if you feel really comfortable with this approach, and it is working for you - then stick with it!

EDIT: It should also be noted that you're second approach will take longer for the browser to render than you're first approach (the browser has to check multiple conditions instead of just one) for more info see this question

like image 44
Sean Avatar answered Sep 21 '22 20:09

Sean


Nope.

What your second code is doing is saying, "target all the elements inside elements that have class top, that have the class wrapper and apply such and such properties"

On the other hand, your first code is only targeting the elements that have the class top-wrapper (or whatever) regardless of their parents class.

like image 40
Juan Cortés Avatar answered Sep 21 '22 20:09

Juan Cortés