管理 CSS 爆炸

发布于 2024-08-21 11:59:36 字数 1700 浏览 8 评论 0 原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

夏至、离别 2024-08-28 11:59:36

这是一个很好的问题。在我看来,CSS 文件在一段时间后往往会失去控制,尤其是但不仅限于在团队中工作时。

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

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

  • 在修复 bug 期间添加 CSS 时,请留下有关更改内容的评论(“这是为了确保该框在 IE < 7 中左对齐”)

  • 避免冗余,例如在 .classname 和 < code>.classname:hover.

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

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

  • 构建合理的类。请参阅下面的一些说明。

  • 使用语义,避免 DIV soup - 例如,使用

      来表示菜单。

  • 在尽可能低的级别上定义所有内容(例如正文中的默认字体系列、颜色和大小),并尽可能使用继承

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

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

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

  • 请勿与一起使用!重要。不仅因为 IE =< 7 无法应对。在复杂的结构中,使用 !important 通常很容易改变无法找到其来源的行为,但对于长期维护来说它是毒药。 p>

构建合理的类

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

我首先应用全局设置:

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 的默认呈现相反)代码>)。此外,所有菜单都没有任何项目符号点 (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 自定义网站和/或应用程序的外观,这是一个很大的优势并节省时间。

  • 如果可能,为每个页面的正文指定一个唯一的类: 这使得向样式表添加特定于页面的调整变得非常容易:

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

    这样,每个菜单项都可以根据其语义上下文来访问样式:无论它是列表中的第一项还是最后一项;是否是当前活动的项目;并按数字。

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

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.

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 .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.

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.

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.

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 tree with 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.

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).

First, define the common characteristics in a class named 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.

Note: you could also use multiple classes for this but Internet Explorer 6 has problems with multiple classes, so this example uses 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.

Miscellaneous HTML tips

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.

  • 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.

Note that this assigning of multiple classes as outlined in the example above does not work properly in IE6. There is a workaround to 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.

你又不是我 2024-08-28 11:59:36

这里只是 4 个示例:

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

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

  • 使用 CSS 预处理器 并将文件作为部分文件进行管理(我个人更喜欢使用 Sass 和 Compass ,但 Less 也很好,还有其他的)
  • 阅读诸如 OOCSSSMACSSBEMgetbem
  • 看看 BootstrapZurb 基金会 是结构化的。并且不要低估不太流行的框架 - Inuit 是一个有趣的框架,但还有很多其他框架。
  • 通过持续集成服务器和/或任务运行程序(如 Grunt 或 Gulp)上的构建步骤来组合/缩小文件。

Here are just 4 examples:

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.

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

  • Use a CSS pre-processor and 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 BEM or getbem.
  • Take a look at how popular CSS frameworks like Bootstrap and Zurb Foundation are structured. And don't discount less popular frameworks - Inuit is 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.
说好的呢 2024-08-28 11:59:36

不要在 CSS 中编写标题,

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

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

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

如果必须编写标题,请在文件开头添加目录。

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

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

在规则内或规则内编写注释,而不是在规则块之外

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

将页面拆分为组件

大多数情况下,组件应该有 position:relative、没有 paddingmargin。这大大简化了 % 规则,并且允许元素的 absolute:position 更简单,因为如果存在绝对定位的容器,则绝对定位的元素在计算 top 时将使用该容器属性。

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

组件也可以被视为页面上的独立单元。用外行人的话说,如果将某些东西视为黑盒有意义,则将其视为组件。

再次使用 QA 页面示例:

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

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

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

例如,bordermarginpadding(但不是 outline)都会添加到元素的尺寸和大小你正在造型。

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

如果它们在一行中不那么可读,至少将它们放在很接近的位置:尽可能

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

使用简写:

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

永远不要重复选择器

如果您有同一选择器的多个实例,那么很可能您将不可避免地得到多个选择器相同规则的实例。例如:

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

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

首先 DIV 和 SPAN 标记是例外:您永远不应该使用它们! ;) 仅使用它们来附加类/id。

这...

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;
}

应该这样写:

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

因为那里额外的悬空 DIV 不会向选择器添加任何内容。他们还强制执行不必要的标签规则。例如,如果您要将 .answerdiv 更改为 article,您的样式就会被破坏。

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

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

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

通用规则是邪恶的!

  • 如果可以的话,避免编写通用/魔法规则,
  • 除非它是用于 CSS 重置/取消重置,所有通用魔法都应该应用于至少一个根组件。

它们不会节省你的时间,它们会让你头爆炸;并使维护成为一场噩梦。当您编写规则时,您可能知道它们适用于哪里,但这并不能保证您的规则以后不会给您带来麻烦。

即使您对正在设计的文档有一些了解,添加到此通用规则也会令人困惑且难以阅读。这并不是说您不应该编写通用规则,只是不要使用它们,除非您确实希望它们是通用的,甚至它们也会向选择器中添加尽可能多的范围信息。

像这样的东西...

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

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

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

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

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

基本上可以这样理解:

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

只要我知道某个组件是页面上的单例,我就喜欢使用 ID;您的需求可能会有所不同。

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

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

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

现在假设你使用分页作为答案列表,你可能会遇到这样的事情

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

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

错误的修复方法是:

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

正确的修复方法是:

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

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

如果你写的是这样的内容:“这个值取决于 blah-blah 与 blah-blah 的高度相结合” ,你不可避免地会犯错误,一切都会像纸牌屋一样倒塌。

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

我如何编写调色板?

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

例如。

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

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

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

使用越少的名称越好。最好使用非常简单(而且简短!)的单词:文本、正文、标题。

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

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

自己清理

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

如果您按照我的建议,将某些容器视为您风格中的黑盒(组件),在选择器中使用这些组件,并将所有内容保存在一个专用文件中(或使用 TOC 和标头正确拆分文件),那么您的工作变得更加容易...

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

保留 unsorted.css 文件

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

这样做的几个原因:

  • 完成后重构会更快,然后搜索规则(可能不存在)并注入代码,
  • 您将编写要删除的内容,注入代码只会使代码变得更难删除附加到原始文件的代码
  • 很容易导致规则/选择器重复

Don't write headings in CSS

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

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 .css files.

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.

/* 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.

Split the page into components

Components should have position:relative, no padding and 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, left properties.

Most DIVs in a HTML5 document are usually a component.

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.

Going with the QA page example again:

#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, margin and padding (but not outline) all add to the dimensions and size of the element you are styling.

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

First off the DIV and SPAN tags are the exception: you should never use them, ever! ;) Only use them to attach a class/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, .answer from a div to a article your style would break.

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-collapse property is a special property that only makes sense when applied to a table. If .statistics is not a table it should not apply.

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

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.

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 pagination component. 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:block the individual page number links and give them a dark gray background. For them to be visible you have to have rules like this:

.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 SASS or LESS.

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.

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 cascade into.

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.

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 .this whenever a element is supposedly "the selected item" or "the current item", etc.

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.

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...

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.

Keep a unsorted.css file

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.css stylesheet then refactor into your answers.css stylesheet.

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
拥醉 2024-08-28 11:59:36

看看
1. SASS
2. 指南针

Have a look at
1. SASS
2. Compass

一直在等你来 2024-08-28 11:59:36

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

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

有些意识形态与最佳答案中所说的很多内容相悖,但是一旦您知道如何以面向对象的方式构建 CSS ,您就会发现它实际上可以保持代码的精简和简洁。意思是。

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

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

另一个好方法在某些方面与 OOCSS 类似,就是从一开始就规划和编写可扩展和模块化的 CSS。 Jonathan Snook 写了一篇关于 SMACSS - CSS 的可扩展和模块化架构

让我为您提供一些链接:
大规模 CSS 的 5 个错误 - (视频)
大规模 CSS 的 5 个错误 - (幻灯片)
CSS 膨胀 -(幻灯片)

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

There's even an OOCSS framework out there that's pretty good.

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 CSS in an object oriented fashion you'll see it actually work at keeping code lean & mean.

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 Sullivan to 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 table based layout into a lot of 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 Snook has done a brilliant write up and book/ebook about SMACSS - Scalable and Modular Architecture for CSS

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

花辞树 2024-08-28 11:59:36

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

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

例如,

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

将使所有这些元素共享字体大小、颜色或任何您的规则。您甚至可以使 #page1 的后代的所有 DIV 都具有特定的规则。

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

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

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

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?

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.

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).

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.

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.

メ斷腸人バ 2024-08-28 11:59:36

我可以建议 Less CSS 动态框架

它类似于前面提到的 SASS。

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

例如,

 #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;
}

May I suggest Less CSS Dynamic framework

It is similar to SASS as mentioned earlier.

It helps maintain CSS per parent class.

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.

Also, #child1 specific CSS belongs to #parent.

This would render to

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

#parent #child2
{
 width: 100%;
 background: #F1F8E2;
 padding: 15px;
}
找个人就嫁了吧 2024-08-28 11:59:36

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

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

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

  2. (否则我发现,对于大多数元素,我至少有一 p>网格系统CSS,如果站点需要的话。 (我的基础是 960.gs

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

  4. 在网站各个地方使用的组件的样式

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

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

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.

I tend to organise my CSS files roughly like this:

  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

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.

硪扪都還晓 2024-08-28 11:59:36

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

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

值得注意的是,这种干净的方法可能与性能问题背道而驰,性能有利于基于 id 或标签名称的短选择器。找到这种平衡取决于你,但除非你有一个庞大的网站,否则这应该只是你脑后的一个指南,提醒你保持选择器简短。 有关性能的更多信息请参见此处

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

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

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

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.

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.

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.

Lastly, are you going to have a single CSS file for 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 page that includes every supported CSS module to test collisions and unintended cascading.

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.

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

心碎的声音 2024-08-28 11:59:36

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

首先,阅读有关高效 CSS 的内容。尝试 Google Page Speed 并阅读 Souders 撰写的有关高效 CSS 的文章。

然后,输入 OOCSS。

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

它将彻底改变编写 CSS 的每一点。我焕然一新并且喜欢它。

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

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.

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

Then, enter OOCSS.

  • Learn to work with the cascade. (After all, we call it Cascading Stylesheets).
  • 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.

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

摇划花蜜的午后 2024-08-28 11:59:36

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

用 SASS 编写。如果你放弃变量、mixin 等的优势,那就太疯狂了。

切勿使用 HTML ID 进行样式设置;始终使用类。如果使用正确,HTML ID 在整个页面中只出现一次,即
与可重用性完全相反——这是最基本的商品之一
合理的工程。此外,重写选择器真的很难
包含 ID,并且通常压制一个 HTML ID 的唯一方法是
创建另一个 ID,导致 ID 在代码库中传播,就像
它们是害虫。最好保留 HTML ID 以保持不变的 Javascript
或集成测试挂钩。

根据 CSS 类的视觉功能而不是其特定于应用程序的功能来命名。例如,说“.highlight-box”
而不是“.bundle-product-discount-box”。以这种方式编码意味着
当您退出时,您可以重新使用现有的样式表
副业。例如,我们一开始是销售法律笔记,但是
最近转为法律导师。我们旧的 CSS 类的名称如下
“.download_document_box”,一个说话时有意义的类名
关于数字文档,但在应用于新的文档时只会造成混乱
私人导师的领域。一个更好的名字,既适合现有的
服务 - 以及任何未来的服务 - 将是“.pretty_callout_box”。

避免在特定的网格信息之后命名 CSS 类。CSS 社区中曾经(并且仍然)存在一种可怕的反模式,即
CSS 框架的设计者和创建者(咳 Twitter Bootstrap
相信“span-2”或“cols-8”是CSS的合理名称
类。 CSS 的重点是给你修改的可能性
您的设计不会(很大程度上)影响标记。硬编码网格
将尺寸写入 HTML 会阻碍这一目标,因此建议不要在任何情况下这样做
项目预计持续时间超过一个周末。更多关于我们如何避免
稍后网格课程。

将 CSS 拆分到多个文件。理想情况下,您会将所有内容拆分为“组件”/“小部件”,然后从这些原子组成页面
设计。但实际上,您会注意到您的某些网站
页面有特质(例如特殊的布局,或奇怪的照片
仅出现在一篇文章中的画廊)。在这些情况下你可能会
创建与该特定页面相关的文件,仅重构为
当清楚该元素将是成熟的小部件时
在其他地方重新使用。这是一种权衡,其动机是
实际预算问题。

最小化嵌套。引入新类而不是嵌套选择器。事实上,SASS 消除了重复选择器的痛苦
嵌套并不意味着您必须嵌套五层深。
切勿过度限定选择器(例如,不要使用“ul.nav”,其中“.nav”
可以做同样的工作。)并且不要在
自定义类名称(例如“h2.highlight”)。相反,只需使用该类
单独命名并删除基本选择器(例如前面的示例
应该是“.highlight”)。过度限定选择器不会添加任何
值。

仅在对基本组件进行样式设置时才为 HTML 元素(例如“h1”)创建样式,该样式应在整个应用程序中保持一致。
避免使用像“header ul”这样的广泛选择器,因为您可能
无论如何,必须在某些地方覆盖它们。正如我们一直说的,大多数
每当您想要使用特定的、名称良好的类时
想要特定的风格。

掌握块元素修饰符的基础知识。您可以在此处阅读有关它的示例。我们很少使用它,但它仍然有帮助
我们经常组织 CSS 样式。

The core principles for sensible CSS, extracted from CSS Refactoring: From append-only to modular 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.

挖个坑埋了你 2024-08-28 11:59:36

很多时候,我会看到有人将文件分成几个部分,并在各部分之间添加标题注释。

像“它”这样的东西

/* Headings and General Text */

.... stuff here for H1, etc..

/* Main page layout */

.... stuff here for layout page setup etc.

效果很好,可以让你以后很容易返回并找到你正在做的事情。

A lot of times I will see individuals break the file out into sections, with a heading comment between sections.

Something like

/* Headings and General Text */

.... stuff here for H1, etc..

/* Main page layout */

.... stuff here for layout page setup etc.

It works pretty well and can make it easy to go back later and find what you are working on.

半葬歌 2024-08-28 11:59:36

您应该查看BEM

理论

BEM 试图提供一组用于组织和命名 css 选择器的指令,以使事物更加可重用和模块化,并避免选择器之间经常导致意大利面条式的冲突代码和特异性令人头痛。

当正确使用它时,它实际上会产生一些非常积极的效果。

  • 当样式添加到元素时,它们会按照您的预期执行样式
  • 不会泄漏,并且仅影响它们添加到的内容
  • 样式与文档结构完全解耦
  • 样式不需要被迫相互覆盖

BEM 工作与 SASS 一起为 CSS 带来近乎面向对象的风格。您可以构建模块化文件,用于处理单个 UI 元素的显示并包含变量(例如颜色)和“方法”(例如如何处理内部元素)。虽然铁杆 OO 程序员可能会对这个想法犹豫不决,但事实上,所应用的概念带来了 OO 结构的许多更好的部分,例如模块化、松散耦合和紧密内聚以及上下文无关的可重用性。您甚至可以使用 Sass 和 以看起来像封装对象的方式构建& 运算符r。

Smashing Magazine 的更深入文章可以在这里找到;以及 CCS Wizardry 的 Harry Roberts 的一篇(任何涉及 css 的人都应该读一读)在这里

在实践中

我已经多次使用过这个,同时也使用过 SMACSS 和 OOCSS,这意味着我也有一些东西可以对它们进行比较。我也曾经历过一些大混乱,通常是我自己、缺乏经验造成的。

当我在现实世界中使用 BEM 时,我会通过一些额外的原则来增强该技术。我利用实用程序类 - 一个很好的例子是包装类:

.page-section {
    width: 100%;
}
@media screen and (min-width: 1200px) {
    margin: 0 auto;
    width: 1200px;
}

而且我也在一定程度上依赖于级联和特异性。这里,BEM 模块将是 .primary-box ,而 .header 将是特定覆盖的上下文

.header {
  .primary-box {
    color: #000;
  }
}

(我尽最大努力使所有内容都通用和上下文尽可能免费,这意味着一个好的项目几乎所有东西都在可重用的模块中)

我在这里要说的最后一点是,无论您的项目看起来多么小和不复杂,您都应该从一开始就这样做,因为两个原因:

  • 项目的复杂性增加,因此奠定良好的基础很重要,
  • 即使是一个看起来很简单的项目,因为它是在 WordPress 上构建的,几乎没有 JavaScript,但 CSS 也包含在内,但 CSS 中仍然可以非常复杂 - 好吧,你不必做任何服务器侧面编码,所以这部分很简单,但是小册子磨损的前端有二十个模块,每个模块有三个变体:那里有一些非常复杂的 CSS!

Web 组件

2015 年,我们开始关注 Web 组件。我对这些还不太了解,但他们希望将所有前端功能整合到独立的模块中,有效地尝试将 BEM 的各种原理应用到整个前端,并将分散但完全耦合的组件化DOM 片段、Js (MVC) 和 CSS 等元素都构建相同的 UI 小部件。

通过这样做,他们将解决 css 存在的一些原始问题,我们尝试使用 BEM 等解决方案,同时使其他一些前端架构更加健全。

此处还有一些进一步的阅读内容,还有一个框架这里的聚合物非常值得一看

最后

我也认为这是一个优秀、现代的 CSS 最佳实践指南 - 专为防止大型 CSS 项目变得混乱而设计。我尝试遵循其中的大部分内容。

You should look at BEM.

Theory

BEM is an attempt to provide a set of instructions for organising and naming css selectors in an attempt to make things more re-usable and modular and to avoid clashes between selectors of the sort that often leads to spaghetti code and specificity headaches.

When it's used correctly it actually has some very positive effects.

  • Styles do what you expect when they're added to an element
  • Styles don't leak and effect only what they're added to
  • Styles are completely decoupled from document structure
  • Styles don't need to be forced to over-ride each other

BEM works well with SASS to bring an almost object oriented style to CSS. You can build modular files, that handle the display of a single UI element and contain variables, such as colours and 'methods' such as how internal elements are handled. While a hardcore OO programmer might balk at this idea, in fact, the applied concepts bring in a lot of the nicer parts of OO structures, such as modularity, loose coupling and tight cohesion and context free re-usability. You can even build in a way that looks like an encapsulated object by using Sass and the & operator.

A more in depth article from Smashing Magazine can be found here; and one from Harry Roberts of CCS Wizardry (who anyone involved in css should have a read of) is here.

In Practice

I've used this, several times, along with having used SMACSS and OOCSS meaning I have something to compare them too. I've also worked in some big messes, often of my own, inexperienced creation.

When I use BEM in the real world I augment the technique with a couple of extra principles. I utilise utility classes - a good example is a wrapper class:

.page-section {
    width: 100%;
}
@media screen and (min-width: 1200px) {
    margin: 0 auto;
    width: 1200px;
}

And I also rely somewhat on the cascade and specificity. Here the BEM module would be .primary-box and the .header would be the context for a specific over-ride

.header {
  .primary-box {
    color: #000;
  }
}

(I try my hardest to make everything as generic and context free as possible, meaning a good project almost everything is in the modules which are re-usable)

One final point I'd make here is that however small and un-complex your project may appear you should do this from the start, for two reasons:

  • projects increase in complexity, so laying good foundations is important, css included
  • even a project that appears simple because it's built on WordPress has little JavaScript can still be very complex in the CSS - OK, you don't have to do any server side coding, so that part is simple, but the brochure-wear front end has twenty modules and three variations of each: you've got some very complex css there!

Web Components

In 2015 we are starting to look at Web Components. I don't know a huge amount about these yet, but they look to bring all front end functionality together in self contained modules, effectively trying to apply the sorts of principles from BEM to the front end as a whole and componentise dispersed but wholly coupled elements such as DOM fragments, Js (MVC) and CSS that all build the same UI widget.

By doing this theyb will address some of the original issues that exist with css which we've tried to solve with things like BEM, while along the way making some of the other front end architecture more sane.

There's some further reading here and also a framework Polymer here which is well worth a look

Finally

I also think this is an excellent, modern best practice css guide - designed specifically for stopping large css projects from getting messy. I try to follow most of these.

人疚 2024-08-28 11:59:36

我建议您查看“Compass Style”CSS 框架

I would recommend you to look at "Compass Style" CSS framework.

残疾 2024-08-28 11:59:36

这里有一些很棒的材料,有些人花了很多时间来回答这个问题,但是当涉及到单独或单独的样式表时,我会使用单独的文件进行开发,然后将整个站点中使用的所有通用 CSS 合并起来部署时放入单个文件中。

这样您就可以两全其美,提高性能(从浏览器请求的 HTTP 请求更少)并在开发时分离代码问题。

there is some great material here and some have taken allot of time in answering this question however when it comes to either seperate or individual style sheets I would go with seperate files for development and then move into have all your generic css used across the sited merged into a single file when deployed.

this way you have the best of both worlds, increases performance (less HTTP requests being requested from the browser) and seperation of code concerns while developing.

假扮的天使 2024-08-28 11:59:36

我使用层叠样式表 (CSS) 已有 20 多年了。因此,下面是我可以帮助您的解决方案:

  1. 通过 标记始终使用外部 CSS。外部 CSS 远远优于“嵌入”

  2. 始终为所有基本 HTML 元素使用“重置”样式表。大多数 CSS 包(例如 Bootstrap 等)都附带重置或重启表。这些重新设计了所有 HTML 元素选择器,使它们在所有浏览器和用户代理上看起来都不错。这使您免去了必须在表单控件、布局、文本等基本元素上重新设计和自定义设计的噩梦。几年前我编写了自己的“重置”表。我将把它发布在 GitHub 上的 "通用 CSS 框架如果你想要我的,很快就会。适用于所有新旧浏览器。
  3. 请记住,所有基于文本的样式都级联继承自然地通过网站元素向下!因此,您应该很少需要重复字体样式、线条-高度等。大多数年轻的开发人员都会忘记这一点。基于文本的样式沿 HTML 树继承,因此只需在父级中写入一次。通常 元素是设置基本字体样式等的最佳位置。
  4. 由于#3,您不需要像 SASS 这样的 CSS 预处理器来重新组织或管理样式表。< /strong> 远离这些第三方依赖项。可以编写 CSS 来继承或级联整个站点的样式,这样您就不必在 CSS 类等之间重复相同的字体样式或属性。
  5. 对控制设计的块级/布局样式进行分组。使用顶级 HTML 块上的 ID 选择器 (#myid) 用于分隔各个部分,并使用 CSS 选择器中的选择器来管理特定于该页面或网站部分的项目 (#main .someclass {...})。它们的优点是易于跟踪和易于分离,但 ID 选择器具有非常高的选择性或重量。 ID 选择器的权重为 1-0-0 或 100,而类的权重为 0-1-0 或 10。这可以防止任何以后的样式转变损坏特定受保护部分中以前的自定义样式。
  6. 围绕可重用​​的单个 CSS 类设计所有 CSS。避免在 CSS 选择器中附加更多元素和类链,除非您绝对需要用自定义类覆盖公共共享类。示例:.articlelink{...} 将是每个人都可以访问的共享通用样式。 .block1 .area2 .articlelink{...} 将允许您在整个部分中创建自定义版本,而无需创建新类或更改 HTML。
  7. 使用 CSS 注释! /* 我的新样式 */ ...后跟相关 CSS 块,或者仅使用注释来解释代码中不直观的内容。
  8. 如果您有大型项目,请让每个开发人员为其部分编写自己的自定义 CSS 表,但继承主网站样式表。首先,确保网站的所有部分都链接到您的基本重置和基础首先是网站表。这允许基本元素样式、字体设置、布局、页面设计、表单和颜色首先由基表强制执行,因此开发人员只需添加所需的新样式,而不是重新发明同一个轮子。当您更新所有开发人员继承的基本表时,这些基本表会毫不费力地自然地出现在项目的所有部分中,并且团队可以立即看到它们。

请记住,您正在使用级联样式表,而不是样式表!这意味着大多数基于文本的样式都被设计为从所有父元素继承,然后将这些相同的样式级联到数千个页面的 HTML 树中,而无需额外的代码。大多数新的 Web 开发人员无法掌握 CSS 的简单性,因此很难使用 SASS 和其他工具来修复它。只是不需要。 CSS 是由非常聪明的人在 20 多年前以这种方式设计的,为您解决了所有这些问题。

如果你真正开始以正确的方式使用 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>

和平

I have been working with Cascading Style Sheets (CSS) for over 20 years. So below is my solution to help you:

  1. 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!
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.

If you really start to use CSS the right way, you find you can erase most of the styles, SASS, minimization, and other external routines and extra code your website once used, while enjoying the cascading effects of CSS that were designed to make minimal coding possible long ago.

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

Peace

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文