tags:

views:

60

answers:

1

I develop Rails based website, enjoying using partials for some common "components"

Recently, i faced a problem, that states with CSS interference.

Styles for one component (described in css) override styles for another components.

For example, one component has ...

<ul class="items">

... and another component has it too. But that ul's has different meaning in these two components.

On the other hand, i want to "inherit" some styles for one component from another.

For example: Let, we have one component, called "post"

<div class="post">
    <!-- post's stuff --> 
    <ul class="items">
        ...
    </ul>
</div

And another component, called "new-post":

<div class="new-post">
    <!-- post's stuff -->
    <ul class="items">
        ...
    </ul>
    <!-- new-post's stuff -->
    <div class="tools">...</div>
</div

Post and new-post have something similar ("post's stuff") and i want to make CSS rules to handle both "post" and "new-post"

New post has "subcomponents", for example - editing tools, that has also:

<ul class="items">

This is where CSS rules starting to interfer - some rules, targeted for ul.items (in post and new-post) applies subcomponent of new-post, called "tools"

On the one hand - i want to inherit some styles

On the other hand, i want to get better incapsulation

What are the best practices, to avoid such kind of problems ?

+4  A: 

Use inheritance to your advantage.

.items { /* common shared styles here */ }
.post .items { /* styles specific to item lists inside a .post div */ }
.new-post .items { /* styles specific to item lists inside a .new-post div */ }

If you want .post lists and .new-post lists to share a style, the ideal way is to add a third class that the two share and style that.

<style type="text/css">
    .items { /* common shared styles here */ }
    .post { /* styles shared by all .post divs */ }

    .old-post { /* styles specific to .old-post divs */ }
    .old-post .items { /* styles specific .item lists inside .old-post divs */ }

    .new-post { /* styles specific to .new-post divs */ }
    .new-post .items { /* styles specific .item lists inside .new-post divs */ }
</style>

<div class="post old-post">
    <ul class="items">...</ul>
</div>

<div class="post new-post">
    <ul class="items">...</ul>
</div>
Chris