开发者

CSS: Importance of specifying object over generic dot?

开发者 https://www.devze.com 2023-01-15 01:10 出处:网络
Given <div class=\"foo\"> <span class=\"bar\"></span> </div> I\'ve always defined the CSS classes as:

Given

<div class="foo">
    <span class="bar"></span>
</div>

I've always defined the CSS classes as:

.f开发者_JAVA技巧oo
{

}
.bar
{

}

Is specifying the object important, or ultimately for readability so you can quickly see which sort of element you are searching for when editing? IE:

div.foo
{

}
span.bar
{

}


It will be important for element specificity.

.foo targets any element that has a class of "foo".

div.foo targets only <div>s that have a class of "foo". That means other elements with that class aren't selected.

If you're sure only one kind of element will ever bear a given class, I guess there's nothing wrong with prefixing the class selector with the element name for readability, or leaving it out completely if you're lazy to type.

However, if you think other elements might bear this class — for instance if it's a pretty generic name like left, larger-font or sep, it's a good idea to do this so you're sure you're styling the right elements.

If there are any common styles shared by any elements with a given class, you specify just the class selector and add the common styles there, then after that specify any styles that pertain to each individual element. For example:

.foo { /* Generic styles for foo class */ }
div.foo { /* Styles for <div>s with foo class */ }
blockquote.foo { /* Styles for <blockquote>s with foo class */ }
0

精彩评论

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

关注公众号