2

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 ?

0

1 Answer 1

7

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.