我一直严重依赖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膨胀的最好方法是使用面向对象的CSS原则。

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

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

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

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

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

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

其他回答

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

它类似于前面提到的SASS。

它帮助维护每个父类的CSS。

E.g.

 #parent{     
  width: 100%;

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

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

它的作用: 将width:100%应用于#child1和#child2。

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

这将导致

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

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

您还应该了解级联、权重以及它们是如何工作的。

我注意到您只使用了类标识符(div.title)。您知道您也可以使用ID,而且ID比类更重要吗?

例如,

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

将使所有这些元素共享一个字体大小,或者颜色,或者任何你的规则。您甚至可以使所有的div都是#page1的后代获得某些规则。

至于重量,请记住CSS轴从最一般/最轻到最特定/最重。也就是说,在CSS选择器中,一个元素说明符被一个类说明符取代,一个ID说明符取代。数字计数,因此具有两个元素说明符(ul li)的选择器将比只有一个说明符(li)的选择器具有更大的权重。

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

顺便说一句,在类中添加元素说明符(div.title)是没有必要的,除非你遇到了与其他具有class="title"的元素冲突。不要增加不必要的重量,因为你以后可能会用到这些重量。

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

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

然后进入OOCSS。

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

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

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

合理CSS的核心原则,摘自CSS重构:从仅追加到模块化CSS

Write in SASS. You'd be insane to forego the advantages of variables, mixins, and so on. Never use an HTML ID for styling; always use classes. HTML IDs, when used correctly, appear only once in the whole page, which is the complete opposite of re-usability — one of the most basic goods in sensible engineering. Moreover, it's really hard to override selectors containing IDs and often the only way to overpower one HTML ID is to create another ID, causing IDs to propagate in the codebase like the pests they are. Better to leave the HTML IDs for unchanging Javascript or integration test hooks. Name your CSS classes by their visual function rather than by their application-specific function. For example, say ".highlight-box" instead of ".bundle-product-discount-box". Coding in this way means that you can re-use your existing style-sheets when you role out side-businesses. For example, we started out selling law notes but recently moved into law tutors. Our old CSS classes had names like ".download_document_box", a class name that makes sense when talking about digital documents but would only confuse when applied to the new domain of private tutors. A better name that fits both existing services — and any future ones — would be ".pretty_callout_box". Avoid naming CSS classes after specific grid information. There was (and still is) a dreadful anti-pattern in CSS communities whereby designers and creators of CSS frameworks (cough Twitter Bootstrap) believe that "span-2" or "cols-8" are reasonable names for CSS classes. The point of CSS is to give you the possibility to modify your design without affecting the markup (much). Hardcoding grids sizes into the HTML thwarts this goal, so it is advised against in any project expected to last longer than a weekend. More on how we avoided grid classes later. Split your CSS across files. Ideally you would split everything into "components"/"widgets" and then compose pages from these atoms of design. Realistically though, you'll notice that some of your website pages have idiosyncrasies (e.g. a special layout, or a weird photo gallery that appears in just one article). In these cases you might create a file related to that specific page, only refactoring into a full-blown widget when it becomes clear that the element will be re-used elsewhere. This is a tradeoff, one that is motivated by practical budgetary concerns. Minimise nesting. Introduce new classes instead of nesting selectors. The fact that SASS removes the pain of repeating selectors when nesting doesn't mean that you have to nest five levels deep. Never over-qualify a selector (e.g. don't use "ul.nav" where ".nav" could do the same job.) And don't specify HTML elements alongside the custom class name (e.g."h2.highlight"). Instead just use the class name alone and drop the base selector (e.g. the previous example should be ".highlight"). Over-qualifying selectors doesn't add any value. Create styles for HTML elements (e.g. "h1") only when styling base components which should be consistent in the whole application. Avoid broad selectors like "header ul" because it's likely that you have to override them in some places anyway. As we keep saying, most of the time you want to use a specific, well-named class whenever you want a particular style. Embrace the basics of Block-Element-Modifier. You can read about it for example on here. We used it quite lightly, but still it helped us a lot in organising CSS styles.

这是一个非常好的问题。在我所看到的任何地方,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。