管理 CSS 爆炸

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2253110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 21:34:35  来源:igfitidea点击:

Managing CSS Explosion

cssorganization

提问by JasCav

I have been heavily relying on CSS for a website that I am working on. Right now, all the CSS styles are being applied on a per tag basis, and so now I am trying to move it to more of an external styling to help with any future changes.

我一直在严重依赖 CSS 来创建我正在开发的网站。现在,所有 CSS 样式都在每个标签的基础上应用,所以现在我试图将它移到更多的外部样式,以帮助将来进行任何更改。

But now the problem is that I have noticed I am getting a "CSS Explosion". It is becoming difficult for me to decide how to best organize and abstract data within the CSS file.

但现在的问题是我注意到我收到了“CSS 爆炸”。我很难决定如何最好地组织和抽象 CSS 文件中的数据。

I am using a large number of divtags within the website, moving from a heavily table-based website. So I'm getting a lot of CSS selectors that look like this:

我在网站中使用了大量div标签,从一个基于表格的网站转移而来。所以我得到了很多看起来像这样的 CSS 选择器:

div.title {
  background-color: blue;
  color: white;
  text-align: center;
}

div.footer {
  /* Styles Here */
}

div.body {
  /* Styles Here */
}

/* And many more */

It's not too bad yet, but as I am a beginner, I was wondering if recommendations could be made on how best to organize the various parts of a CSS file. I don't want to have a separate CSS attribute for every element on my website, and I always want the CSS file to be fairly intuitive and easy to read.

还不错,但由于我是初学者,我想知道是否可以就如何最好地组织 CSS 文件的各个部分提出建议。我不想为我网站上的每个元素都有一个单独的 CSS 属性,我总是希望 CSS 文件相当直观且易于阅读。

My ultimate goal is to make it easy to use the CSS files and demonstrate their power to increase the speed of web development. This way, other individuals that may work on this site in the future will also get into the practice of using good coding practices, rather than having to pick it up the way I did.

我的最终目标是让 CSS 文件更容易使用,并展示它们提高 Web 开发速度的能力。这样,将来可能在此站点上工作的其他人也将开始使用良好的编码实践,而不必像我那样学习。

采纳答案by Pekka

This is a very good question. Everywhere I look, CSS files tend to get out of control after a while—especially, but not only, when working in a team.

这个问题问得好。无论我看到哪里,CSS 文件都会在一段时间后失去控制——尤其是,但不仅限于,在团队中工作时。

The following are the rules I myself am trying to adhere to (not that I always manage to.)

以下是我自己试图遵守的规则(并非我总是设法遵守。)

  • Refactor early, refactor often.Frequently clean up CSS files, fuse together multiple definitions of the same class. Remove obsolete definitions immediately.

  • When adding CSS during fixing bugs, leave a comment as to what the change does ("This is to make sure the box is left aligned in IE < 7")

  • Avoid redundancies, e.g. defining the same thing in .classnameand .classname:hover.

  • Use comments /** Head **/to build a clear structure.

  • Use a prettifier tool that helps maintain a constant style. I use Polystyle, with which I'm quite happy (costs $15 but is money well spent). There are free ones around as well (e.g. Code Beautifierbased on CSS Tidy, an open-source tool).

  • Build sensible classes. See below for a few notes on this.

  • Use semantics, avoid DIV soup - use <ul>s for menus, for example.

  • Define everything on as low a level as possible (e.g. a default font family, colour and size in the body) and use inheritwhere possible

  • If you have very complex CSS, maybe a CSS pre-compiler helps. I'm planning to look into xCSSfor the very same reason soon. There are several others around.

  • If working in a team, highlight the necessity of quality and standards for CSS files as well. Everybody's big on coding standards in their programming language(s), but there is little awareness that this is necessary for CSS too.

  • If working in a team, doconsider using Version Control. It makes things that much easier to track, and editing conflicts that much easier to solve. It's really worth it, even if you're "just" into HTML and CSS.

  • Do not work with !important. Not only because IE =< 7 can't deal with it. In a complex structure, the use of !importantis often tempting to change a behaviour whose source can't be found, but it's poisonfor long-term maintenance.

  • 尽早重构,经常重构。经常清理 CSS 文件,将同一类的多个定义融合在一起。立即删除过时的定义。

  • 在修复错误期间添加 CSS 时,对更改的作用发表评论(“这是为了确保框在 IE < 7 中左对齐”)

  • 避免冗余,例如在.classname和 中定义相同的内容.classname:hover

  • 使用注释/** Head **/来构建清晰的结构。

  • 使用有助于保持风格不变的美化工具。我使用Polystyle,对此我很满意(花费 15 美元,但物有所值)。周围也有免费的(例如基于CSS Tidy 的Code Beautifier,一个开源工具)。

  • 建立合理的班级。有关这方面的一些注意事项,请参见下文。

  • 使用语义,避免 DIV 汤 -<ul>例如,将s 用于菜单。

  • 在尽可能低的级别定义所有内容(例如 中的默认字体系列、颜色和大小body)并inherit在可能的情况下使用

  • 如果您有非常复杂的 CSS,也许 CSS 预编译器会有所帮助。出于同样的原因,我打算很快研究xCSS。周围还有其他几个。

  • 如果在团队中工作,还要强调 CSS 文件质量和标准的必要性。每个人都热衷于他们的编程语言的编码标准,但很少意识到这对于 CSS 也是必要的。

  • 如果在团队中工作,考虑使用版本控制。它使事情更容易跟踪,编辑冲突更容易解决。这真的很值得,即使您“只是”使用 HTML 和 CSS。

  • 不要使用!important. 不仅因为 IE =< 7 无法处理。在复杂的结构中,使用!important往往很容易改变一种无法找到来源的行为,但它对长期维护来说却是毒药

Building sensible classes

建立合理的班级

This is how I like to build sensible classes.

这就是我喜欢构建合理类的方式。

I apply global settings first:

我首先应用全局设置:

body { font-family: .... font-size ... color ... }
a { text-decoration: none; }

Then, I identify the main sections of the page's layout—e.g. the top area, the menu, the content, and the footer. If I wrote good markup, these areas will be identical to the HTML structure.

然后,我确定页面布局的主要部分——例如顶部区域、菜单、内容和页脚。如果我编写了好的标记,这些区域将与 HTML 结构相同。

Then, I start building CSS classes, specifying as much ancestry as possible as long as it is sensible, and grouping related classes as closely as possible.

然后,我开始构建 CSS 类,在合理的情况下尽可能多地指定祖先,并尽可能将相关类分组。

div.content ul.table_of_contents 
div.content ul.table_of_contents li 
div.content ul.table_of_contents li h1
div.content ul.table_of_contents li h2
div.content ul.table_of_contents li span.pagenumber

Think of the whole CSS structure as a treewith increasingly specific definitions the further away from the root you are. You want to keep the number of classes as low as possible, and you want to repeat yourself as seldom as possible.

把整个 CSS 结构想象成一棵树,离根越远,定义就越具体。您希望保持尽可能少的课程数量,并希望尽可能少地重复自己。

For example, let's say you have three levels of navigational menus. These three menus look different, but they also share certain characteristics. For example, they are all <ul>, they all have the same font size, and the items are all next to each other (as opposed to the default rendering of an ul). Also, none of the menus has any bullet points (list-style-type).

例如,假设您有三级导航菜单。这三个菜单看起来不同,但它们也有一些共同点。例如,它们都是<ul>,它们都具有相同的字体大小,并且项目都彼此相邻(与 的默认呈现相反ul)。此外,所有菜单都没有任何要点 ( list-style-type)。

First, define the commoncharacteristics in a class named menu:

首先,在名为 的类中定义共同特征menu

div.navi ul.menu { display: ...; list-style-type: none; list-style-image: none; }
div.navi ul.menu li { float: left }

then, define the specific characteristics of each of the three menus. Level 1 is 40 pixels tall; levels 2 and 3, 20 pixels.

然后,定义三个菜单中每一个的具体特征。级别 1 是 40 像素高;第 2 级和第 3 级,20 个像素。

Note:you could also use multiple classes for this but Internet Explorer 6 has problems with multiple classes, so this example uses ids.

注意:您也可以为此使用多个类,但 Internet Explorer 6存在多个类的问题,因此本示例使用ids。

div.navi ul.menu#level1 { height: 40px; }
div.navi ul.menu#level2 { height: 20px; }
div.navi ul.menu#level3 { height: 16px; }

The markup for the menu will look like this:

菜单的标记如下所示:

<ul id="level1" class="menu"><li> ...... </li></ul>
<ul id="level2" class="menu"><li> ...... </li></ul>
<ul id="level3" class="menu"><li> ...... </li></ul>

If you have semantically similar elements on the page—like these three menus—try to work out the commonalities first and put them into a class; then, work out the specific properties and apply them to classes, or, if you have to support Internet Explorer 6, ID's.

如果页面上有语义相似的元素——比如这三个菜单——试着先找出共同点并将它们放在一个类中;然后,计算出特定的属性并将它们应用到类,或者,如果您必须支持 Internet Explorer 6,则应用 ID。

Miscellaneous HTML tips

其他 HTML 提示

If you add these semantics to your HTML output, designers can later customize the look of web sites and/or apps using pure CSS, which is a great advantage and time-saver.

如果您将这些语义添加到您的 HTML 输出中,设计人员可以稍后使用纯 CSS 自定义网站和/或应用程序的外观,这是一个很大的优势和节省时间。

  • If possible, give every page's body a unique class: <body class='contactpage'>this makes it very easy to add page-specific tweaks to the style sheet:

    body.contactpage div.container ul.mainmenu li { color: green }
    
  • When building menus automatically, add as much CSS context as possible to allow extensive styling later. For example:

    <ul class="mainmenu">
     <li class="item_first item_active item_1"> First item </li> 
     <li class="item_2"> Second item </li> 
     <li class="item_3"> Third item </li> 
     <li class="item_last item_4"> Fourth item </li> 
    </ul>
    

    This way, every menu item can be accessed for styling according to its semantic context: Whether it's the first or last item in the list; Whether it's the currently active item; and by number.

  • 如果可能,给每个页面的主体一个唯一的类:<body class='contactpage'>这样可以很容易地向样式表添加页面特定的调整:

    body.contactpage div.container ul.mainmenu li { color: green }
    
  • 自动构建菜单时,请添加尽可能多的 CSS 上下文,以便以后进行广泛的样式设置。例如:

    <ul class="mainmenu">
     <li class="item_first item_active item_1"> First item </li> 
     <li class="item_2"> Second item </li> 
     <li class="item_3"> Third item </li> 
     <li class="item_last item_4"> Fourth item </li> 
    </ul>
    

    这样,每个菜单项都可以根据其语义上下文访问以进行样式设置:它是列表中的第一项还是最后一项;是否为当前活动项;并按编号。

Notethat this assigning of multiple classes as outlined in the example above does not work properly in IE6. There is a workaroundto make IE6 able to deal with multiple classes. If the workaround is not an option, you will have to set the class that is most important to you (item number, active or first/last), or resort to using IDs.

请注意,上面示例中概述的多个类的这种分配在 IE6 中无法正常工作。有一种解决方法可以使 IE6 能够处理多个类。如果解决方法不是一个选项,您将必须设置对您最重要的类(项目编号、活动或第一个/最后一个),或者求助于使用 ID。

回答by Andy Ford

Here are just 4 examples:

这里仅举4个例子:

On all 4 my answer has included the advice to download and read Natalie Downe's PDF CSS Systems. (The PDF includes tons of notes not in the slides, so read the PDF!). Take note of her suggestions for organization.

在所有 4 个答案中,我的回答都包括下载和阅读 Natalie Downe 的 PDF CSS Systems 的建议。(PDF 包含大量不在幻灯片中的注释,因此请阅读 PDF!)。注意她的组织建议。

EDIT (2014/02/05)four years later, I'd say:

四年后编辑(2014/02/05),我会说:

  • Use a CSS pre-processorand manage your files as partials (I personally prefer Sass with Compass, but Less is quite good as well and there are others)
  • Read up on concepts like OOCSS, SMACSS, and BEMor getbem.
  • Take a look at how popular CSS frameworks like Bootstrapand Zurb Foundationare structured. And don't discount less popular frameworks - Inuitis an interesting one but there are plenty others.
  • Combine/minify your files with a build step on a continuous integration server and/or a task runner like Grunt or Gulp.
  • 使用 CSS 预处理器并将文件作为部分管理(我个人更喜欢 Sass 和 Compass,但 Less 也很好,还有其他的)
  • 阅读OOCSSSMACSSBEMgetbem等概念。
  • 看看流行的 CSS 框架(如BootstrapZurb Foundation)是如何构建的。不要忽视不太流行的框架 - Inuit是一个有趣的框架,但还有很多其他框架。
  • 使用持续集成服务器和/或 Grunt 或 Gulp 等任务运行器上的构建步骤合并/缩小您的文件。

回答by srcspider

Don't write headings in CSS

不要在 CSS 中写标题

Just split sections into files. Any CSS comments, should be just that, comments.

只需将部分拆分为文件即可。任何 CSS 注释都应该是注释。

reset.css
base.css
somepage.css
someotherpage.css
some_abstract_component.css

Use a script to combine them into one; if necessary. You can even have a nice directory structure as well, and just have your script recursively scan for .cssfiles.

使用脚本将它们合二为一;如有必要。您甚至可以拥有一个不错的目录结构,只需让您的脚本递归扫描.css文件即可。

If you must write headings, have a TOC at the start of the file

如果你必须写标题,在文件的开头有一个目录

The headings in the TOC should be perfectly equal to headings you write later. It's a pain to search for headings. To add to the problem, how exactly is anyone suppose to know you have another header after your first header? ps. don't add doc-like * (star) at the start of each line when writing TOCs, it just makes it more annoying to select the text.

TOC 中的标题应该与您稍后编写的标题完全相同。搜索标题很痛苦。更重要的是,在第一个标题之后,人们究竟是如何知道您还有另一个标题的?附:编写目录时不要在每行的开头添加类似 doc 的 *(星号),只会让选择文本变得更烦人。

/* Table of Contents
   - - - - - - - - -
   Header stuff
   Body Stuff
   Some other junk
   - - - - - - - - -
 */
...
/* Header Stuff 
 */
...
/* Body Stuff 
 */

Write comments with or within the rules, not outside the block

在规则内或在规则内写评论,而不是在块外

First off, when you edit the script there is a 50/50 chance you'll pay attention to what is outside the rule block (particularly if it's a big glob of text ;) ). Secondly there is (almost) no case where you would need a "comment" outside. If it is outside, it is 99% of the time a title, so keep it like that.

首先,当您编辑脚本时,您有 50/50 的机会会注意规则块之外的内容(特别是如果它是一大堆文本 ;) )。其次,(几乎)没有任何情况下您需要在外面进行“评论”。如果它在外面,那么 99% 的时间都是标题,所以保持这样。

Split the page into components

将页面拆分为组件

Components should have position:relative, no paddingand no margin, most of the time. This simplifies % rules a lot, as well as allowing for much simpler absolute:position'ing of elements, since if there's a absolute positioned container the absolute positioned element will use the container when computing top, right, bottom, leftproperties.

大多数情况下position:relative,组件应该有, nopadding和 no margin。这大大简化了 % 规则,并允许更简单absolute:position的元素 'ing,因为如果有绝对定位的容器,绝对定位的元素将在计算top, right, bottom,left属性时使用该容器。

Most DIVs in a HTML5 document are usually a component.

HTML5 文档中的大多数 DIV 通常是一个组件。

A component is also something that can be considered a independent unit on the page. In laymen's terms treat something like a component if it makes sense to treat something like a blackbox.

组件也可以被认为是页面上的一个独立单元。用外行的话来说,如果将某物视为一个blackbox是有意义的,则将其视为一个组件。

Going with the QA page example again:

再次使用 QA 页面示例:

#navigation
#question
#answers
#answers .answer
etc.

By splitting the page into components, you split your work into manageable units.

通过将页面拆分为组件,您可以将工作拆分为可管理的单元。

Put rules with a cumulative effect on the same line.

将具有累积效应的规则放在同一行上。

For example border, marginand padding(but not outline) all add to the dimensions and size of the element you are styling.

例如bordermarginpadding(但不是outline)都添加到您正在设置样式的元素的尺寸和大小。

position: absolute; top: 10px; right: 10px;

If they are just not that readable on one line, at least put them in close proximity:

如果它们在一行上不那么易读,至少将它们放在附近:

padding: 10px; margin: 20px;
border: 1px solid black;

Use shorthand when possible:

尽可能使用速记:

/* the following... */
padding-left: 10px;
padding-right: 10px;
/* can simply be written as */
padding: 0 10px;

Never repeat a selector

永远不要重复选择器

If you have more instances of the same selector, there's a good chance you'll inevitable end up with multiple instances of the same rules. For example:

如果您有更多相同选择器的实例,则很有可能最终会出现相同规则的多个实例。例如:

#some .selector {
    margin: 0;
    font-size: 11px;
}
...
#some .selector {
    border: 1px solid #000;
    margin: 0;
}

Avoid using TAGs as selectors, when you can use id/classes

当您可以使用 id/classes 时,避免使用 TAGs 作为选择器

First off the DIV and SPAN tags are the exception: you should never use them, ever! ;) Only use them to attach a class/id.

首先 DIV 和 SPAN 标签是个例外:你永远不应该使用它们,永远!;) 仅使用它们来附加类/ID。

This...

这个...

div#answers div.answer table.statistics {
    border-collapse: collapsed;
    color: pink;
    border: 1px solid #000;
}
div#answers div.answer table.statistics thead {
    outline: 3px solid #000;
}

Should be written like this:

应该这样写:

#answers .answer .statistics {
    border-collapse: collapsed;
    color: pink;
    border: 1px solid #000;
}
#answers .answer .statistics thead {
    outline: 3px solid #000;
}

Because the extra dangling DIVs there add nothing to the selector. They also force a unnecessary tag-rule. If you were to change, for example, .answerfrom a divto a articleyour style would break.

因为那里额外的悬空 DIV 不会向选择器添加任何内容。他们还强制执行不必要的标签规则。例如,如果您.answer要从 a更改为a divarticle您的样式就会中断。

Or if you prefer more clarity:

或者,如果您希望更清晰:

#answers .answer .statistics {
    color: pink;
    border: 1px solid #000;
}
#answers .answer table.statistics {
    border-collapse: collapsed;
}
#answers .answer .statistics thead {
    outline: 3px solid #000;
}

The reason being the border-collapseproperty is a special property that only makes sense when applied to a table. If .statisticsis not a tableit should not apply.

原因是该border-collapse属性是一个特殊属性,只有在应用于 a 时才有意义table。如果.statistics不是,table则不应适用。

Generic rules are evil!

通用规则是邪恶的!

  • avoid writing generic/magic rules if you can
  • unless it's for a CSS-reset/unreset, all your generic magic should apply to at least one root component
  • 如果可以,请避免编写通用/魔法规则
  • 除非是用于 CSS 重置/取消重置,否则您所有的通用魔法都应该应用于至少一个根组件

They don't save you time, they make your head explode; as well as make maintenance a nightmare. When you're writing the rule, you may know where they apply, however that has no guarantee your rule won't mess with you later on.

它们不会为您节省时间,只会让您头疼;以及使维护成为一场噩梦。当您编写规则时,您可能知道它们适用于何处,但这并不能保证您的规则以后不会打扰您。

To add to this generic rules are confusing and hard to read, even if you have some idea of the document you're styling. This is not to say you shouldn't write generic rules, just don't use them unless you truly intend for them to be generic, and even them add as much scope information into the selector as you can.

添加到这个通用规则是令人困惑和难以阅读的,即使您对要设计的文档有一些想法。这并不是说你不应该编写通用规则,只是不要使用它们,除非你真的希望它们是通用的,甚至它们也会尽可能多地将范围信息添加到选择器中。

Stuff like this...

像这样的东西...

.badges {
    width: 100%;
    white-space: nowrap;
}

address {
    padding: 5px 10px;
    border: 1px solid #ccc;
}

...has the same problem as using global variables in a programing language. You need to give them scope!

...与在编程语言中使用全局变量有同样的问题。你需要给他们范围!

#question .userinfo .badges {
    width: 100%;
    white-space: nowrap;
}

#answers .answer .userinfo address {
    padding: 5px 10px;
    border: 1px solid #ccc;
}

Basically that reads as:

基本上是这样写的:

components                   target
---------------------------- --------
#answers .answer   .userinfo address
-------- --------- --------- --------
domain   component component selector 

I like using IDs whenever a component I know is a singleton on a page; your needs may be different.

我喜欢在我知道的组件是页面上的单例时使用 ID;您的需求可能有所不同。

Note: Ideally, you should write just enough. Mentioning more components in the selector however is the more forgiving mistake, compared to mentioning less components.

注意:理想情况下,您应该编写足够的内容。然而,与提及较少的组件相比,在选择器中提及更多的组件是更宽容的错误。

Lets assume you have a paginationcomponent. You use it in many places across your site. This would be a good example of when you would be writing a generic rule. Lets say you display:blockthe individual page number links and give them a dark gray background. For them to be visible you have to have rules like this:

假设您有一个pagination组件。您可以在网站的许多地方使用它。这将是您何时编写通用规则的一个很好的例子。假设您display:block是单个页码链接,并为它们提供深灰色背景。为了让它们可见,你必须有这样的规则:

.pagination .pagelist a {
    color: #fff;
}

Now lets say you use your pagination for a list of answers, you may encounter something like this

现在假设您将分页用于答案列表,您可能会遇到这样的事情

#answers .header a {
    color: #000;
}
...
.pagination .pagelist a {
    color: #fff;
}

This will make your white links black, which you don't want.

这将使您的白色链接变黑,这是您不想要的。

The incorrect way to fix it is:

错误的修复方法是:

.pagination .pagelist a {
    color: #fff !important;
}

The correct way to fix it is:

正确的修复方法是:

#answers .header .pagination .pagelist a {
    color: #fff;
}

Complex "logic" comments don't work :)

复杂的“逻辑”注释不起作用:)

If you write something like: "this value is dependent on blah-blah combined with height of blah-blah", it's just inevitable you'll make a mistake and it will all fall down like a house of cards.

如果你写这样的话:“这个值取决于等等等等的高度结合等等等等”,你不可避免地会犯错,它会像纸牌屋一样倒塌。

Keep your comments simple; if you need "logical operations" consider one of those CSS templating languages like SASSor LESS.

保持你的评论简单;如果您需要“逻辑操作”,请考虑使用其中一种 CSS 模板语言,例如SASSLESS

How do you do I write a color pallet?

你如何写一个调色板?

Leave this for the end. Have a file for your entire color pallet. With out this file your style should still have some usable color-pallet in the rules. Your color pallet should overwrite. You chain selectors using a very high level parent component (eg. #page) and then write your style as a self sufficient rule block. It can be just color or something more.

把这个留到最后。为您的整个调色板准备一个文件。没有这个文件,你的样式在规则中仍然应该有一些可用的调色板。你的颜色托盘应该覆盖。您使用非常高级的父组件(例如#page)链接选择器,然后将您的样式编写为自给自足的规则块。它可以只是颜色或更多。

eg.

例如。

#page #header .description,
#page #categories .description,
#page #answers .answer .body
{
    color: #222; background: #fff; 
    border-radius: 10px;
    padding: 1em;
}

The idea is simple, your color pallet is a stylesheet independent of the base style, which you cascadeinto.

这个想法很简单,您的调色板是一个独立于基本样式的样式表,您可以将其级联到其中。

Less names, requires less memory, making the code easier to read

更少的名称,需要更少的内存,使代码更易于阅读

Using fewer names is better. Ideally use very simple (and short!) words: text, body, header.

使用较少的名称更好。理想情况下使用非常简单(且简短!)的词:文本、正文、标题。

I also find combination of simple words is easier to understand then having a soup of long "appropriate" words: postbody, posthead, userinfo, etc.

我还发现简单单词的组合更容易理解,然后是“适当”的长词汤:postbody、posthead、userinfo 等。

Keep the vocabulary small, this way even if some stranger coming in to read your style-soup (like yourself after a few weeks ;)) only needs to understand where words are used rather where every selector is used. For example I use .thiswhenever a element is supposedly "the selected item" or "the current item", etc.

保持词汇量小,这样即使某个陌生人进来阅读您的风格汤(就像几周后的您一样 ;))只需要了解单词的使用位置而不是每个选择器的使用位置。例如,.this每当一个元素应该是“所选项目”或“当前项目”等时,我都会使用。

Clean up after yourself

清理后自己

Writing CSS is like eating, sometimes you leave a mess behind. Make sure you clean up that mess, or the garbage code will just pile up. Remove classes/ids you don't use. Remove CSS rules you don't use. Make sure everything is nice a tight and you don't have conflicting or duplicated rules.

编写 CSS 就像吃饭一样,有时你会留下一团糟。确保你清理了那些乱七八糟的东西,否则垃圾代码就会堆积起来。删除您不使用的类/ID。删除您不使用的 CSS 规则。确保一切都很好,并且没有相互冲突或重复的规则。

If you, as I suggested, treated some containers as black-boxes (components) in your style, used those components in your selectors, and kept everything in one dedicated file (or properly split a file with a TOC and headers), then your work is substantially easier...

如果您按照我的建议将某些容器视为您风格中的黑盒(组件),在您的选择器中使用这些组件,并将所有内容保存在一个专用文件中(或正确拆分带有 TOC 和标题的文件),那么您的工作轻松多了……

You can use a tool such as the firefox extension Dust-Me Selectors (tip: point it to your sitemap.xml) to help you find some of the junk hidden in your css nukes and carnies.

您可以使用诸如 firefox 扩展 Dust-Me Selectors(提示:将其指向您的 sitemap.xml)之类的工具来帮助您找到一些隐藏在您的 css nukes 和 carnies 中的垃圾。

Keep a unsorted.cssfile

保存unsorted.css文件

Say you are styling a QA site, and you already have a stylesheet for the "answers page", which we will call answers.css. If you now need to add a lot of new css, add it to the unsorted.cssstylesheet then refactor into your answers.cssstylesheet.

假设您正在为 QA 站点设计样式,并且您已经有了“答案页面”的样式表,我们将其称为answers.css。如果您现在需要添加大量新 css,请将其添加到unsorted.css样式表中,然后重构到您的answers.css样式表中。

Several reasons for this:

造成这种情况的几个原因:

  • it's faster to refactor in after you're finished, then it is to search for rules (that probably don't exist) and inject code
  • you will write stuff that you will remove, injecting code just makes it harder to remove that code
  • appending to the original file easily leads to rule/selector duplication
  • 完成后重构更快,然后是搜索规则(可能不存在)并注入代码
  • 您将编写将要删除的内容,注入代码只会使删除该代码变得更加困难
  • 附加到原始文件很容易导致规则/选择器重复

回答by Zimbabao

Have a look at 1. SASS2. Compass

看看 1. SASS2.指南针

回答by Moin Zaman

The best way I've seen to counter CSSbloat is using Object Oriented CSS principles.

我见过的对抗CSS膨胀的最好方法是使用面向对象的 CSS 原则。

There's even an OOCSSframework out there that's pretty good.

甚至还有一个非常好的OOCSS框架。

Some of the ideologies go against a lot of what's been said here in the top answers but once you know how to architect CSSin an object oriented fashion you'll see it actually work at keeping code lean & mean.

一些意识形态与顶级答案中的许多内容背道而驰,但是一旦您知道如何以CSS面向对象的方式进行架构,您就会发现它实际上可以保持代码的精简和平均。

The key thing here is to identify 'Objects' or building block patterns in your site and architect with them.

这里的关键是在您的站点中识别“对象”或构建块模式,并使用它们进行架构。

Facebook hired the creator of OOCSS, Nicole Sullivanto get a lot of savings in their front end code (HTML / CSS). Yes you can actually get savings not only in your CSS, but in your HTML too, which by the sound of it, is very possible for you as you mention converting a tablebased layout into a lot of div's

Facebook 聘请了 OOCSS 的创建者Nicole Sullivan,以节省大量前端代码(HTML / CSS)。是的,您实际上不仅可以节省 CSS,还可以节省 HTML,从它的声音来看,这对您来说非常有可能,因为您提到将table基于布局的布局转换为许多div's

Another great approach is similar in some aspects to OOCSS, is to plan and write your CSS to be scalable and modular from the start. Jonathan Snookhas done a brilliant write up and book/ebook about SMACSS - Scalable and Modular Architecture for CSS

另一个很棒的方法在某些方面类似于 OOCSS,是从一开始就计划和编写 CSS 以使其具有可扩展性和模块化。Jonathan Snook写了一篇关于SMACSS - CSS 的可扩展和模块化架构的精彩文章和书籍/电子书

Let me hook you up with some links:
5 mistakes of massive CSS - (Video)
5 mistakes of massive CSS - (Slides)
CSS Bloat - (Slides)

让我给你一些链接:
5 个大量 CSS 的错误 -(视频)
5 个大量 CSS 的错误 -(幻灯片)
CSS Bloat -(幻灯片)

回答by Robusto

You should also understand the cascade, and weight, and how they work.

您还应该了解级联、权重以及它们的工作原理。

I notice you are using only class identifiers (div.title). Did you know that you can use IDs as well, and that an ID carries more weight than a class?

我注意到您仅使用类标识符 (div.title)。您是否知道也可以使用 ID,并且 ID 比类具有更大的权重?

For example,

例如,

#page1 div.title, #page1 ul, #page1 span {
  // rules
}

will make all those elements share a font-size, say, or a color, or whatever your rules are. You can even make all the DIVs that are descendants of #page1 get certain rules.

将使所有这些元素共享字体大小,例如,颜色,或任何您的规则。您甚至可以使所有作为#page1 后代的 DIV 获得某些规则。

As to weight, remember that the CSS axes move from most-general/lightest to most-specific/heaviest. That is, in a CSS selector an element specifier is overruled by a class specifier is overruled by an ID specifier. Numbers count, so a selector with two element specifiers (ul li) will have more weight than one with only a single specifier (li).

至于权重,请记住 CSS 轴从最一般/最轻到最具体/最重。也就是说,在 CSS 选择器中,元素说明符被类说明符否决,而 ID 说明符则被否决。数字很​​重要,因此具有两个元素说明符 (ul li) 的选择器将比只有一个说明符 (li) 的选择器具有更大的权重。

Think of it like digits. A 9 in the ones column is still less than a one in the tens column. A selector with an ID specifier, a class specifier, and two element specifiers, will have more weight than a selector with no ID, 500 class specifiers and 1,000 element specifiers. This is an absurd example, of course, but you get the idea. The point is, applying this concept helps you clean up a lot of CSS.

把它想象成数字。个列中的 9 仍然小于十位列中的 1。具有 ID 说明符、类说明符和两个元素说明符的选择器将比没有 ID、500 个类说明符和 1,000 个元素说明符的选择器具有更大的权重。当然,这是一个荒谬的例子,但你明白了。关键是,应用这个概念可以帮助您清理大量 CSS。

BTW, adding the element specifier to the class (div.title) is not necessary unless you are running into conflicts with other elements that have class="title". Don't add unnecessary weight, because you may need to use that weight later.

顺便说一句,除非您与其他具有 class="title" 的元素发生冲突,否则不需要向类 (div.title) 添加元素说明符。不要增加不必要的重量,因为您以后可能需要使用该重量。

回答by Abhishek Mehta

May I suggest Less CSS Dynamic framework

我可以建议Less CSS 动态框架吗

It is similar to SASS as mentioned earlier.

它类似于前面提到的 SASS。

It helps maintain CSS per parent class.

它有助于维护每个父类的 CSS。

E.g.

例如

 #parent{     
  width: 100%;

    #child1
    {    
     background: #E1E8F2;    
     padding: 5px;    
    }

    #child2
   {
     background: #F1F8E2;
     padding: 15px
   }
 }

What this does: Applies width:100% to both #child1 and #child2.

这样做的作用:将宽度:100% 应用于 #child1 和 #child2。

Also, #child1 specific CSS belongs to #parent.

此外,#child1 特定的 CSS 属于 #parent。

This would render to

这将呈现为

#parent #child1
{
 width: 100%;
 background: #E1E8F2;
 padding: 5px;
}

#parent #child2
{
 width: 100%;
 background: #F1F8E2;
 padding: 15px;
}

回答by Paul D. Waite

I find the difficult thing is translating the required design for a site into a series of rules. If the site's design is clear and rules-based, then your class names and CSS structure can flow from that. But if people are, over time, randomly adding little bits to the site that don't make much sense, there's not a lot you can do about that in the CSS.

我发现困难的是将网站所需的设计转化为一系列规则。如果站点的设计清晰且基于规则,那么您的类名和 CSS 结构就可以从中借鉴。但是,如果人们随着时间的推移,向站点随机添加一些没有多大意义的内容,那么您在 CSS 中就无能为力了。

I tend to organise my CSS files roughly like this:

我倾向于像这样大致组织我的 CSS 文件:

  1. CSS reset, based on Eric Meyer's. (Because otherwise I find that, for most elements, I've got at least one or two rules that are just resetting default browser styles — most of my lists don't look like the default HTML style for lists, for example.)

  2. Grid system CSS, if the site calls for it. (I base mine on 960.gs)

  3. Styles for components that appear on every page (headers, footers, etc)

  4. Styles for components that are used in various places across the site

  5. Styles that are only relevant on individual pages

  1. CSS 重置,基于Eric Meyer 的. (因为否则我发现,对于大多数元素,我至少有一个或两个规则只是重置默认浏览器样式 - 例如,我的大多数列表看起来不像列表的默认 HTML 样式。)

  2. 网格系统 CSS,如果站点需要它。(我基于960.gs

  3. 出现在每个页面上的组件样式(页眉、页脚等)

  4. 在整个站点的不同地方使用的组件的样式

  5. 仅与个别页面相关的样式

As you can see, most of that depends on the design for the site. If the design's clear and organised, your CSS can be. If not, you're screwed.

如您所见,其中大部分取决于网站的设计。如果设计清晰且有条理,那么您的 CSS 就可以。如果没有,你就完蛋了。

回答by G-Wiz

My answer is high-level to address the high-level concerns you've raised in your question. There may be low-level organizational tricks and tweak you can do to make it prettier, but none of those can fix methodological deficiencies. There are several things that affect CSS explosion. Obviously the overall complexity of the site, but also things like naming semantics, CSS performance, CSS file organization, and testability/acceptability.

我的回答是高层次的,以解决您在问题中提出的高层次问题。可能有一些低级的组织技巧和调整可以使它更漂亮,但这些都不能解决方法论的缺陷。有几件事会影响 CSS 爆炸。显然,网站的整体复杂性,还有命名语义、CSS 性能、CSS 文件组织和可测试性/可接受性等。

You seem to be on the right path with naming semantics, but it can be taken a step further. Sections of HTML that appear repeatedly on the site without structural modification (known as "modules") can be considered selector roots, and from there you can scope the internal layout relative to that root. This is the basic tenet of object-oriented CSS, and you can read/watch more about it in this talk by a Yahoo engineer.

您似乎在命名语义方面走在正确的道路上,但还可以更进一步。在没有结构修改的情况下重复出现在站点上的 HTML 部分(称为“模块”)可以被视为选择器根,从那里您可以相对于该根确定内部布局的范围。这是面向对象 CSS的基本原则,您可以在 Yahoo 工程师的这个演讲中阅读/观看更多关于它的内容

It's important to note that this clean approach can run opposite of the concern of performance, which favors short selectors based either on id or tag name. Finding that balance is up to you, but unless you have a massive site, this should just be a guide in the back of your head reminding you to keep your selectors short. More about performance here.

重要的是要注意,这种干净的方法可能与性能问题相反,后者有利于基于 id 或标签 name 的短选择器。找到平衡取决于你,但除非你有一个庞大的网站,否则这应该只是你脑后的一个指南,提醒你保持选择器的简短。 更多关于这里的性能

Lastly, are you going to have a single CSS filefor your entire site, or multiple files (a single base file used with per-page or -section files)? The single file is better for performance, but might be harder to understand/maintain with multiple team members, and might be harder to test. For testing, I recommend you have a single CSS-test pagethat includes every supported CSS module to test collisions and unintended cascading.

最后,您是要为整个站点使用一个 CSS 文件,还是多个文件(与每个页面或 -section 文件一起使用的单个基本文件)?单个文件的性能更好,但可能更难理解/维护多个团队成员,并且可能更难测试。对于测试,我建议您有一个CSS 测试页面,其中包含每个受支持的 CSS 模块来测试冲突和意外级联。

Alternatively you can have a multiple file approach, to scope the CSS rules to a page or a section. This requires the browser to download multiple files which is a performance issue. You can use server-side programming to specify and aggregate (and minify) the CSS files into a single file dynamically. But since these files are separate and the testing for them would be separate, you introduce the possibility of inconsistent look and feel across pages/sections. Thus testing becomes harder.

或者,您可以使用多文件方法,将 CSS 规则范围限定到页面或部分。这需要浏览器下载多个文件,这是一个性能问题。您可以使用服务器端编程来动态指定和聚合(和缩小)CSS 文件到单个文件中。但由于这些文件是分开的,并且对它们的测试也是分开的,因此您可能会在页面/部分之间引入不一致的外观和感觉。因此测试变得更加困难。

It's up to you to analyze the customer's specific needs, balance these concerns accordingly.

由您来分析客户的特定需求,并相应地平衡这些问题。

回答by madr

As said before me: Get into OOCSS. Sass/Less/Compass is tempting to use, but until vanilla CSS is used the right way Sass/Less/Compass will only get things worse.

正如我之前所说:进入 OOCSS。Sass/Less/Compass 很容易使用,但除非以正确的方式使用 vanilla CSS,否则 Sass/Less/Compass 只会让事情变得更糟。

First of all, read up about efficient css. try Google Page Speed and read what Souders have written about efficient css.

首先,阅读有关高效 css 的信息。试试 Google Page Speed 并阅读 Souders 关于高效 css 的文章。

Then, enter OOCSS.

然后,输入 OOCSS。

  • Learn to work with the cascade. (After all, we call it CascadingStylesheets).
  • Learn how to get the granularity right (bottom-up rather than top-down)
  • Learn how to separate structure and skin (what is unique, and what are the variations of these objects?)
  • Learn how to separate container and content.
  • Learn to love grids.
  • 学习使用级联。(毕竟,我们称之为级联样式表)。
  • 了解如何获得正确的粒度(自下而上而不是自上而下)
  • 学习如何分离结构和皮肤(什么是独特的,这些物体有哪些变化?)
  • 了解如何分离容器和内容。
  • 学会爱网格。

It will revolutionize every single bit about writing css. I am totally renewed and love it.

它将彻底改变有关编写 css 的每一点。我完全焕然一新并喜欢它。

UPDATE: SMACSS is similar to OOCSS, but easier to adapt generally speaking.

更新:SMACSS 类似于 OOCSS,但一般来说更容易适应。