DADU DADU - 7 months ago 11
HTML Question

CSS styling conflict prevention and namespacing techniques

Say you're building a conceptual widget named Awesome Widget and you want to completely protect it from conflicting with either surrounding elements or child elements that reside as content inside the widget.

What we don't want

div ul li {}


Solution 1: CSS child combinator

Using the CSS child combinator selector to specify that only direct children should be targeted.

.awesomewidget > div > ul > li {}


Solution 2: class namespacing

Using aw (Awesome Widget) as the namespace for each class, decreasing the chance of any other elements on the page using that exact namespace + classname.

.awesomewidget .aw-container .aw-list .aw-listitem {}


There's also something like @namespace in CSS but that's only for XML.

Besides solution 1 and 2, are there any others that can be used? Which one would you prefer? Any best practises?

EDIT: example of a problem that arises without proper namespacing / styling conflict prevention

Widget styling:

.awesomewidget > div ul li {
background-color:red;
}


User styling:

ul li {
background-color:blue;
}


Markup:

<div class="awesomewidget">
<div>

<ul>
<li>
<!-- user content starts here -->

<p>I am the user and I want to add some content here. Let's add a list:</p>

<ul>
<li>Why is this list-item red and not blue?</li>
</ul>

<!-- user content ends here -->
</li>
<li>
<!-- user content starts here -->

<!-- user content ends here -->
</li>
</ul>

</div>
</div>

Answer

I would prefer to use a combination of the two solutions like:

.awesomewidget > div ul li {}

Because the second one adds a LOT of unecessary weight to the markup.

Update

For your example, I would add a wrapper around the user content with class .user and then prepend their CSS with .user. However, this is not graceful, it adds some markup, and I think it would be prone to failure.

Comments