3

I've created a widget that people can use on their site which is working nicely, the problem I have is that some of my css is being modified by previously defined classes on some of those websites, here's what I have:

.widget ul { margin:0; }
.widget li { margin:0; }

This is fine until someone places the widget in a container that already has a different margin for all ul elements, like this:

.container ul { margin:10px; }

This ul style is affecting the one on my widget. Is there a way to don't allow those previously defined styles to affect mine?

4

3 回答 3

4

Use more specific selectors in your CSS, and maybe consider using an ID. This will ensure that your selector more specifically targets the elements in your widget, and overrides the more 'vague' selectors of the person's website.

#mywidget .widget > ul {margin:0;}

You might want to ensure that the elements such as the <ul> have their own classes as well, that way you can ensure that you have specific style rules for them rather than allowing them to fall back to whatever the person has in their own CSS.

#mywidget ul.mywidget-list {margin:0;}

Maybe consider using !important as well, but the first solution is probably preferable, in case people are actually trying to override your styles.

.widget ul {margin:0 !important;}

And lastly, I assume you're not actually doing this, but don't use vague class names which the person might use for their own markup, or which may clash with other third party widgets and systems. Use really specific class names and IDs which are likely only to be used by your widget.

Everything above is just an example, as it is hard to give you an exact solution for your particular markup and your widget's usage within other people's sites. I would experiment and get yourself familiar with how the styles are inherited and how different approaches will affect the cascading of styles.

于 2013-10-25T14:09:11.317 回答
0

Ideally, each code block should be self contained. This is what people using the OOCSS and BEM are trying to solve.

Instead of .widget ul, you might write .widget--list

Same thing with container. You might write .container--list

Here are some articles to peruse:

http://csswizardry.com/2013/01/mindbemding-getting-your-head-round-bem-syntax/

https://github.com/csswizardry/CSS-Guidelines

于 2013-10-25T14:10:14.300 回答
-1

It's bad practice, but you could use !important.

.widget ul { margin:0 !important; }
.widget li { margin:0 !important; }
于 2013-10-25T14:08:59.813 回答