开发者

CSS !important rule use, specificity

开发者 https://www.devze.com 2023-02-13 08:27 出处:网络
I am writing a bunch of PHP classes which will be used to create a Wordpress plugin, but can also be used in any othe开发者_开发问答r environment. After testing my script by itself, all seems well, bu

I am writing a bunch of PHP classes which will be used to create a Wordpress plugin, but can also be used in any othe开发者_开发问答r environment. After testing my script by itself, all seems well, but when I created a WP plugin for it, there were CSS conflicts that I had foreseen. I initially planned on using specificity to solve these, but it can't always be done. This is in the default WP theme:

#content tr td {
    border-top: 1px solid #E7E7E7;
    padding: 6px 24px;
}

If I try to specify a td to have no padding, it won't work unless I add an ID to my table, rather than a class. I have seen popular plugins that implemented the !important rule on every single CSS property rather than using an ID for specificity. Which is best? I know the !important rule should be used sparingly, but adding an ID to my table seems to go against semantics, since there will be multiple instances of this table with the same ID:

The ID attribute of a document language allows authors to assign an identifier to one element instance in the document tree.

http://www.w3.org/TR/CSS2/selector.html#id-selectors

EDIT: An alternative may also be to wrap everything in a div with an ID, but if there exists a rule #content #main td or similar, it will still dominate over my #someid td. Also, as discussed below, it is not valid to have two elements sharing the same ID, although it may "work".


As I've said in the comments, you can include the #content rule in your selector together with a class to override the original styles if #content is the wrapper element (and it should be, since if is added to all table elements than there won't be any way of adding more than one table to WordPress posts, which would be... weird).

Anyway, if you have to choose between adding ids to multiple elements, and using !important on your properties, I would use !important for the simple reason that while !important may make your stylesheets unmaintainable, adding multiple ids may also break any JavaScript used on the page, and there's no guarantee that the id selector implementation in all browsers can accommodate multiple elements with the same id, so the consequences are more severe.

Basically, choosing between one highly-unrecommanded-but-otherwise-valid practise and invalid, undefined behavior.

0

精彩评论

暂无评论...
验证码 换一张
取 消