我一直严重依赖CSS的一个网站,我正在工作。现在,所有的CSS样式都是在每个标签的基础上应用的,所以现在我试图将它移动到更多的外部样式,以帮助任何未来的变化。

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

我在网站中使用了大量的div标签,从一个基于表格的网站。我得到了很多这样的CSS选择器:

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

div.footer {
  /* Styles Here */
}

div.body {
  /* Styles Here */
}

/* And many more */

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

我的最终目标是使它易于使用CSS文件,并证明他们的力量,以提高web开发的速度。这样,将来可能在这个网站上工作的其他人也将开始使用良好的编码实践,而不必像我一样学习。


当前回答

我已经使用级联样式表(CSS)超过20年了。所以下面是我的解决方案来帮助你:

ALWAYS use External CSS via a <link> tag. External CSS is far superior to "embedded" <style> and "inline" element styles <span style="color:blue;">my text</span> simply because external styles downloaded to the browser are cached for every page in your website and affect all web pages, not just one. Consider moving all those styles sprinkled throughout your website to CSS classes in your sheets. Make sure you add selectors to increase their weight in cases where they might have cascaded over earlier inherited styles. Note: Many JavaScript API's like Angular and others use embedded CSS which means they are slower and have to reload CSS every refresh or revisit to the site. Bad design! ALWAYS use a "Reset" Style Sheet for all your basic HTML Elements. Most CSS packages like Bootstrap and others come with a reset or reboot sheet. These restyle all your HTML element selectors so they look decent across all browsers and user agents. This saves you the nightmare of having to restyle and customize design across basic elements like form controls, layouts, text, etc. I wrote my own "reset" sheet years ago. I am going to post it on GitHub under "Universal CSS Framework" soon if you would like mine. Works in all the old and new browsers. Remember, all text-based styles cascade and inherit naturally down through the sites elements! So, you should rarely need to repeat font styles, line-heights, etc. Most young developers forget this. Text-based styles are inherited down the HTML tree so only have to be written one time in a parent. Often the <body> element is the best placed to set basic font styles, etc. Because of #3 you do NOT need CSS precrocessors like SASS to reorganize or manage your style sheets. Stay away from these third-party dependencies. CSS can be written to inherit or cascade styles through the site so you do not have to repeat the same font styling or properties across CSS classes, etc. Group your Block Level/Layout styles that control design. Use ID selectors (#myid) on top level HTML blocks to separate sections and use those in CSS selectors to manage items specific to that page or website section (#main .someclass {...}). These have the advantage that they are easy to track and easy to segregate, but ID selectors have very high selectivity or weight. ID selectors have a 1-0-0 or 100 weight over class which has 0-1-0 or 10 weight. This prevents any later style shifts from damaging your previous custom styles in specific protected sections. Design all CSS around a Single CSS Class that can be Reused. Avoid attaching more element and chains of classes in CSS selectors until you absolutely need to override a common shared class with a custom one. Example: .articlelink{...} would be the shared universal style everyone can access. .block1 .area2 .articlelink{...} would allow you to create a custom version throughout a section without creating a new class or changing the HTML. Use CSS Comments! /* My New Styles */ ...followed by blocks of related CSS or just use comments to explain what is not intuitive in your code. If you have big projects, have each developer write their own custom CSS sheets for their sections, but inherit the main site style sheets. First, make sure all sections of the website link to your basic reset and base site sheets first. This allows basic element styles, font settings, layout, page design, forms, and colors to be enforced by the base sheets first so developers only add new styles needed rather than reinventing the same wheel. As you update the base sheets all developers inherit, those appear naturally across all sections of the project with no effort, and the teams can see those instantly.

Remember, you are working with cascading style sheets, not style sheets! That means most text-based styles are designed to inherit from all the parent elements, then cascade those same styles down into your trees of HTML across thousands of pages with no extra code. Most new web developers fail to grasp the simplicity of CSS, so struggle with SASS and other tools to fix it. It just is not needed. CSS was designed this way over 20 years ago by very smart people that solved all these issues for you.

如果你真的开始以正确的方式使用CSS,你会发现你可以删除大部分样式,SASS,最小化,以及其他外部例程和你的网站曾经使用过的额外代码,同时享受CSS的级联效果,这些效果在很久以前就被设计为使最小代码成为可能。

<html>
  <body style="color:blue;">
    <main>
      <section>
        <div>
          <div>
            <div>
              <p>hello blue world</p>
            </div>
          </div>
        </div>
      </section>
    </main>
  </body>
</html>

和平

其他回答

就像我之前说的:进入OOCSS。Sass/Less/Compass使用起来很诱人,但在正确使用CSS之前,Sass/Less/Compass只会让事情变得更糟。

首先,阅读高效css。尝试谷歌页面速度和阅读Souders关于高效css的文章。

然后进入OOCSS。

学会使用级联。(毕竟,我们称之为级联样式表)。 学习如何获得正确的粒度(自底向上而不是自顶向下) 学习如何分离结构和皮肤(什么是唯一的,这些对象的变化是什么?) 学习如何分离容器和内容。 学会爱上网格。

它将彻底改变css的每一个细节。我完全焕然一新,爱上了它。

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

我发现最难的事情是将网站所需的设计转化为一系列规则。如果站点的设计清晰且基于规则,那么你的类名和CSS结构就可以由此而来。但是,如果人们随着时间的推移,随机地在网站上添加一些没有多大意义的内容,那么在CSS中就没有太多办法了。

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

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.) Grid system CSS, if the site calls for it. (I base mine on 960.gs) Styles for components that appear on every page (headers, footers, etc) Styles for components that are used in various places across the site Styles that are only relevant on individual pages

如你所见,这主要取决于网站的设计。如果设计清晰有条理,你的CSS也可以做到。如果不是,你就完蛋了。

这是一个非常好的问题。在我所看到的任何地方,CSS文件都倾向于在一段时间后失去控制——尤其是,但不仅仅是在团队中工作时。

以下是我自己努力遵守的规则(并不是说我总能做到)。

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 .classname and .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 Beautifier based 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 inherit where possible If you have very complex CSS, maybe a CSS pre-compiler helps. I'm planning to look into xCSS for 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, do consider 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 !important is often tempting to change a behaviour whose source can't be found, but it's poison for long-term maintenance.

构建合理的类

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

我首先应用全局设置:

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

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

然后,我开始构建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

你可以把整个CSS结构想象成一棵树,它的定义越远越具体。你想要尽可能地减少课程的数量,并且尽可能少地重复学习。

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

首先,在一个名为menu的类中定义公共特征:

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

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

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

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

菜单的标记看起来像这样:

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

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

其他HTML技巧

如果你将这些语义添加到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.

请注意,如上例中所述的多个类的分配在IE6中不能正常工作。有一个变通方案可以使IE6能够处理多个类。如果没有解决方法,则必须设置对您来说最重要的类(项目编号、活动或第一个/最后一个),或者使用id。

我的回答是高水平的,针对你刚才提到的高水平的关切。也许你可以通过一些低级的组织技巧和调整来使它更漂亮,但这些都不能解决方法上的缺陷。有几个因素会影响CSS的爆炸。显然是网站的整体复杂性,但还有像命名语义、CSS性能、CSS文件组织和可测试性/可接受性等问题。

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

需要注意的是,这种干净的方法可能与性能问题相反,它倾向于基于id或标记名的短选择器。找到平衡取决于你,但除非你有一个庞大的网站,这应该只是一个指南在你的脑后提醒你保持你的选择器简短。这里有更多关于性能的信息。

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

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

由你来分析客户的具体需求,并相应地平衡这些问题。

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

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

一些意识形态与上面的答案相悖,但一旦你知道如何以面向对象的方式构建CSS,你就会发现它实际上有助于保持代码的精简和平均。

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

Facebook聘请了OOCSS的创建者Nicole Sullivan,以节省大量的前端代码(HTML / CSS)。是的,你实际上可以得到节省,不仅在你的CSS,但在你的HTML太,这是由它的声音,是非常有可能为你,因为你提到转换一个基于表格的布局到很多div的

另一个很好的方法在某些方面与OOCSS类似,就是从一开始就计划和编写可伸缩和模块化的CSS。Jonathan Snook写了一本关于SMACSS的书/电子书——CSS的可伸缩和模块化架构

让我给你介绍一些链接: 海量CSS的5个错误-(视频) 海量CSS的5个错误(幻灯片) CSS膨胀-(幻灯片)