我应该如何组织我的 CSS 文件的内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/146106/
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
How should I organize the contents of my CSS file(s)?
提问by Adam Bellaire
This question is about organizing the actual CSS directives themselves within a .css file. When developing a new page or set of pages, I usually just add directives by hand to the .css file, trying to refactor when I can. After some time, I have hundreds (or thousands) of lines and it can get difficult to find what I need when tweaking the layout.
这个问题是关于在 .css 文件中组织实际的 CSS 指令本身。在开发一个新页面或一组页面时,我通常只是手动将指令添加到 .css 文件中,尽可能地尝试重构。一段时间后,我有数百(或数千)行,在调整布局时很难找到我需要的东西。
Does anyone have advice for how to organize the directives?
有没有人有关于如何组织指令的建议?
- Should I try to organize top-down, mimicking the DOM?
- Should I organize functionally, putting directives for elements that support the same parts of the UI together?
- Should I just sort everything alphabetically by selector?
- Some combination of these approaches?
- 我应该尝试自顶向下组织,模仿 DOM 吗?
- 我应该按功能组织,将支持 UI 相同部分的元素的指令放在一起吗?
- 我应该按选择器的字母顺序对所有内容进行排序吗?
- 这些方法的某种组合?
Also, is there a limit to how much CSS I should keep in one file before it might be a good idea to break it off into separate files? Say, 1000 lines? Or is it always a good idea to keep the whole thing in one place?
另外,在将其拆分为单独的文件可能是个好主意之前,我应该在一个文件中保留多少 CSS 是否有限制?比如说,1000 行?还是将整个事物放在一个地方总是一个好主意?
Related Question: What's the best way to organize CSS rules?
相关问题:组织 CSS 规则的最佳方式是什么?
采纳答案by mercator
Have a look at these three slideshare presentations to start:
看看这三个幻灯片演示文稿开始:
Firstly, and most importantly, document your CSS. Whatever method you use to organize your CSS, be consistent and document it. Describe at the top of each file what is in that file, perhaps providing a table of contents, perhaps referencing easy to search for unique tags so you jump to those sections easily in your editor.
首先,也是最重要的,记录你的 CSS。无论您使用什么方法来组织 CSS,都要保持一致并记录下来。在每个文件的顶部描述该文件中的内容,可能提供目录,可能引用易于搜索的唯一标签,以便您在编辑器中轻松跳转到这些部分。
If you want to split up your CSS into multiple files, by all means do so. Oli already mentioned that the extra HTTP requests can be expensive, but you can have the best of both worlds. Use a build script of some sort to publish your well-documented, modular CSS to a compressed, single CSS file. The YUI Compressorcan help with the compression.
如果您想将 CSS 拆分为多个文件,请务必这样做。Oli 已经提到额外的 HTTP 请求可能很昂贵,但您可以两全其美。使用某种构建脚本将文档齐全的模块化 CSS 发布到压缩的单个 CSS 文件中。在锐压缩机可以压缩帮助。
In contrast with what others have said so far, I prefer to write each property on a separate line, and use indentation to group related rules. E.g. following Oli's example:
与到目前为止其他人所说的相比,我更喜欢将每个属性写在单独的行上,并使用缩进将相关规则分组。例如以下奥利的例子:
#content {
/* css */
}
#content div {
/* css */
}
#content span {
/* css */
}
#content etc {
/* css */
}
#header {
/* css */
}
#header etc {
/* css */
}
That makes it easy to follow the file structure, especially with enough whitespace and clearly marked comments between groups, (though not as easy to skim through quickly) and easy to edit (since you don't have to wade through single long lines of CSS for each rule).
这使得遵循文件结构变得很容易,尤其是在组之间有足够的空白和清晰标记的注释(虽然不是那么容易快速浏览)并且易于编辑(因为你不必费力地浏览单行 CSS每个规则)。
Understand and use the cascadeand specificity(so sorting your selectors alphabetically is right out).
理解并使用级联和特异性(因此按字母顺序对选择器进行排序是正确的)。
Whether I split up my CSS into multiple files, and in what files depends on the size and complexity of the site and the CSS. I always at least have a reset.css
. That tends to be accompanied by layout.css
for general page layout, nav.css
if the site navigation menus get a little complicated and forms.css
if I've got plenty of CSS to style my forms. Other than that I'm still figuring it out myself too. I might have colors.css
and type.css/fonts.css
to split off the colors/graphics and typography, base.css
to provide a complete base style for all HTML tags...
是否将我的 CSS 拆分为多个文件,以及在哪些文件中,取决于站点和 CSS 的大小和复杂性。我总是至少有一个reset.css
. 如果站点导航菜单变得有点复杂并且我有很多 CSS 来设置表单的样式layout.css
,nav.css
那么这往往伴随着一般的页面布局forms.css
。除此之外,我自己也在想办法。可能我colors.css
和type.css/fonts.css
拆断的颜色/图形和排版,base.css
为所有的HTML标签提供完整的基本样式...
回答by wusher
I tend to orgainize my css like this:
我倾向于像这样组织我的 css:
- reset.css
- base.css: I set the layout for the main sections of the page
- general styles
- Header
- Nav
- content
- footer
- additional-[page name].css: classes that are used only in one page
- 重置.css
- base.css:我为页面的主要部分设置布局
- 一般风格
- 标题
- 导航
- 内容
- 页脚
- 附加-[页面名称].css:仅在一页中使用的类
回答by Oli
However you find it easiest to read!
但是,您发现它最容易阅读!
Seriously, you'll get a billion and five suggestions but you're only going to like a couple of methods.
说真的,你会得到十亿零五条建议,但你只会喜欢几种方法。
Some things I shall say though:
不过我还是要说几句:
- Breaking a CSS file into chunks does help you organise it in your head, but it means more requests from browsers, which ultimately leads to a slower running server (more requests) and it takes browsers longer to display pages. Keep that in mind.
- Breaking up a file just because it's an arbitrary number of lines is silly (with the exception that you have an awful editor - in which case, get a new one)
- 将 CSS 文件分成块确实有助于您在头脑中组织它,但这意味着来自浏览器的更多请求,最终导致服务器运行速度变慢(更多请求),并且浏览器显示页面需要更长的时间。记在脑子里。
- 仅仅因为它是任意行数就拆分文件是愚蠢的(除了你有一个糟糕的编辑器 - 在这种情况下,换一个新的)
Personally I code my CSS like this:
我个人像这样编写我的 CSS:
* { /* css */ }
body { /* css */ }
#wrapper { /* css */ }
#innerwrapper { /* css */ }
#content { /* css */ }
#content div { /* css */ }
#content span { /* css */ }
#content etc { /* css */ }
#header { /* css */ }
#header etc { /* css */ }
#footer { /* css */ }
#footer etc { /* css */ }
.class1 { /* css */ }
.class2 { /* css */ }
.class3 { /* css */ }
.classn { /* css */ }
Keeping rules on one line allows me to skim down a file very fast and see what rules there are. When they're expanded, I find it too much like hard work trying find out what rules are being applied.
将规则放在一行上可以让我快速浏览文件并查看有哪些规则。当它们被扩展时,我发现这太像努力找出正在应用的规则。
回答by Chris Spittles
There are a number of recognised methodologies for formatting your CSS. Its ultimately up to you what you feel most comfortable writing but these will help manage your CSS for larger more complicated projects. Not that it matters, but I tend to use a combination of BEM and SMACSS.
有许多公认的用于格式化 CSS 的方法。最终取决于你最舒服的写作方式,但这些将有助于为更大、更复杂的项目管理你的 CSS。这并不重要,但我倾向于使用 BEM 和 SMACSS 的组合。
BEM (Block, Element, Modifier)
BEM(块、元素、修改器)
BEM is a highly useful, powerful and simple naming convention to make your front-end code easier to read and understand, easier to work with, easier to scale, more robust and explicit and a lot more strict.
BEM 是一种非常有用、强大且简单的命名约定,它使您的前端代码更易于阅读和理解,更易于使用,更易于扩展,更健壮和明确,并且更加严格。
Block
堵塞
Standalone entity that is meaningful on its own such as:
本身就有意义的独立实体,例如:
header, container, menu, checkbox, input
Element
元素
Parts of a block and have no standalone meaning. They are semantically tied to its block:
块的一部分,没有独立的意义。它们在语义上与其块相关联:
menu item, list item, checkbox caption, header title
Modifier
修饰符
Flags on blocks or elements. Use them to change appearance or behavior:
块或元素上的标志。使用它们来改变外观或行为:
disabled, highlighted, checked, fixed, size big, color yellow
OOCSS
OOCSS
The purpose of OOCSS is to encourage code reuse and, ultimately, faster and more efficient stylesheets that are easier to add to and maintain.
OOCSS 的目的是鼓励代码重用,并最终提供更容易添加和维护的更快、更高效的样式表。
OOCSS is based on two main principles:
OOCSS 基于两个主要原则:
- Separation of structure from skin
- 结构与皮肤的分离
This means to define repeating visual features (like background and border styles) as separate “skins” that you can mix-and-match with your various objects to achieve a large amount of visual variety without much code. See the module object and its skins.
这意味着将重复的视觉特征(如背景和边框样式)定义为单独的“皮肤”,您可以将其与各种对象混合搭配,无需太多代码即可实现大量视觉变化。查看模块对象及其皮肤。
- Separation of containers and content
- 容器和内容物的分离
Essentially, this means “rarely use location-dependent styles”. An object should look the same no matter where you put it. So instead of styling a specific with .myObject h2 {...}, create and apply a class that describes the in question, like . This gives you the assurance that: (1) all unclassed s will look the same; (2) all elements with the category class (called a mixin) will look the same; and 3) you won't need to create an override style for the case when you actually do want .myObject h2 to look like the normal .
从本质上讲,这意味着“很少使用与位置相关的样式”。不管你把它放在哪里,一个对象看起来应该是一样的。因此,不要使用 .myObject h2 {...} 为特定对象设置样式,而是创建并应用一个描述相关问题的类,例如 . 这为您提供了以下保证:(1) 所有未分类的 s 看起来都一样;(2) 具有类别类(称为mixin)的所有元素看起来都一样;和 3) 当您确实希望 .myObject h2 看起来像正常的 .myObject h2 时,您不需要为这种情况创建覆盖样式。
SMACSS
社会保障协会
SMACSS is a way to examine your design process and as a way to fit those rigid frameworks into a flexible thought process. It is an attempt to document a consistent approach to site development when using CSS.
At the very core of SMACSS is categorization. By categorizing CSS rules, we begin to see patterns and can define better practices around each of these patterns.
SMACSS 是一种检查您的设计过程的方法,也是一种将这些严格的框架融入灵活的思维过程的方法。它试图记录使用 CSS 时一致的站点开发方法。
SMACSS 的核心是分类。通过对 CSS 规则进行分类,我们开始看到模式,并且可以围绕这些模式中的每一个定义更好的实践。
There are five types of categories:
有五种类型的类别:
/* Base */
/* Layout */
/* Modules */
/* State */
/* Theme */
BaseContains reset and default element styles. It can also have base styles for controls such as buttons, grids etc which can be overwritten later in the document under specific circumstances.
Base包含重置和默认元素样式。它还可以具有按钮、网格等控件的基本样式,这些样式可以在特定情况下稍后在文档中覆盖。
LayoutWould contain all the navigation, breadcrumbs, sitemaps etc etc.
布局将包含所有导航、面包屑、站点地图等。
ModulesContain area specific styles such as contact form styles, homepage tiles, product listing etc etc etc.
模块包含区域特定样式,例如联系表单样式、主页磁贴、产品列表等。
StateContains state classes such as isSelected, isActive, hasError, wasSuccessful etc etc.
State包含状态类,例如 isSelected、isActive、hasError、wasSuccessful 等。
ThemeContains any styles that are related to theming.
主题包含与主题相关的任何样式。
There are too many to detail here but have a look at these others as well:
这里有太多细节需要详细说明,但也可以看看其他的:
回答by Nick Sergeant
I've tried a bunch of different strategies, and I always come back to this style:
我尝试了很多不同的策略,我总是回到这种风格:
.class {border: 1px solid #000; padding: 0; margin: 0;}
This is the friendliest when it comes to a large amount of declarations.
当涉及到大量声明时,这是最友好的。
回答by Jonathan Arkell
I go with this order:
我按照这个顺序去:
- General style rules, usually applied to the bare elements (a, ul, ol, etc.) but they could be general classes as well (.button, .error)
- Page layout rules applied to most/all pages
- Individual page layout rules
- 通用样式规则,通常应用于裸元素(a、ul、ol 等),但它们也可以是通用类(.button、.error)
- 应用于大多数/所有页面的页面布局规则
- 个人页面布局规则
For any of the style rules that apply to a single page, or a small grouping pages, I will set the body to an id and a class, making it easy to target particular pages. The id is the base name of the file, and the class is the directory name where it is in.
对于适用于单个页面或小分组页面的任何样式规则,我会将主体设置为 id 和类,以便轻松定位特定页面。id 是文件的基本名称,而 class 是它所在的目录名称。
回答by Shog9
Factor out common styles. Not styles that just happen to be the same, styles that are intendedto be the same - where changing the style for one selector will likely mean you'll want to change the other as well. I put an example of this style in another post: Create a variable in CSS file for use within that CSS file.
排除常见的样式。不是恰好相同的样式,而是旨在相同的样式 - 更改一个选择器的样式可能意味着您也想更改另一个。我在另一篇文章中放了一个这种风格的例子: 在 CSS 文件中创建一个变量以在该 CSS 文件中使用。
Apart from that, group related rules together. And split your rules into multiple files... unless everypage actually needs everyrule.
除此之外,将相关规则组合在一起。并将您的规则拆分为多个文件...除非每个页面实际上都需要每个规则。
回答by cllpse
CSS files are cached on the client. So it's good practice to keep all of your styles in one file. But when developing, I find it useful to structure my CSS according to domains.
CSS 文件缓存在客户端上。因此,将所有样式保存在一个文件中是一种很好的做法。但是在开发时,我发现根据域来构建我的 CSS 很有用。
For instance: reset.css
, design.css
, text.css
and so forth. When I release the final product, I mash all the styles into one file.
例如:reset.css
,design.css
,text.css
等等。当我发布最终产品时,我将所有样式混合到一个文件中。
Another useful tip is to focus readability on the rules, not the styles.
另一个有用的提示是将可读性集中在规则上,而不是样式上。
While:
尽管:
ul li
{
margin-left: 10px;
padding: 0;
}
Looks good, it's not easy finding the the rules when you've got, say, 100 lines of code.
看起来不错,当你有 100 行代码时,要找到规则并不容易。
Instead I use this format:
相反,我使用这种格式:
rule { property: value; property: value; }
rule { property: value; property: value; }
回答by allesklar
Here is what I do. I have a CSS index page with no directives on it and which calls the different files. Here is a short sample:
这就是我所做的。我有一个没有指令的 CSS 索引页,它调用不同的文件。这是一个简短的示例:
@import url("stylesheet-name/complete-reset.css");
@import url("stylesheet-name/colors.css");
@import url("stylesheet-name/structure.css");
@import url("stylesheet-name/html-tags.css");
@import url("stylesheet-name/menu-items.css");
@import url("stylesheet-name/portfolio.css");
@import url("stylesheet-name/error-messages.css");
It starts with a complete reset. The next file defines the color palette for easy reference. Then I style the main <div/>
s that determine the layout, header, footer, number of columns, where they fit, etc... The html tags definses <body/>
, <h1/>
, <p/>
, t etc... Next come the specific sections of the site.
它从完全重置开始。下一个文件定义了调色板以便于参考。然后我设计<div/>
确定布局、页眉、页脚、列数、它们适合的位置等的 main s 的样式... html 标签定义了<body/>
、<h1/>
、<p/>
、 t 等... 接下来是站点的特定部分。
It's very scalabale and very clear. Much more friendly to find code to change and to a dd new sections.
它非常可扩展且非常清晰。查找要更改的代码和添加新部分更加友好。
回答by Tim Booker
As the actual ordering is a vital part of how your CSS is applied, it seems a bit foolish to go ahead with the "alphabetical" suggestion.
由于实际的排序是如何应用 CSS 的重要部分,所以继续使用“按字母顺序”的建议似乎有点愚蠢。
In general you want to group items together by the area of the page they affect. E.g. main styles that affect everything go first, then header and footer styles, then navigation styles, then main content styles, then secondary content styles.
通常,您希望按项目影响的页面区域将项目组合在一起。例如,影响一切的主要样式首先出现,然后是页眉和页脚样式,然后是导航样式,然后是主要内容样式,然后是次要内容样式。
I would avoid breaking into multiple files at this point, as it can be more difficult to maintain. (It's very difficult to keep the cascade order in your head when you have six CSS files open). However, I would definitely start moving styles to different files if they only apply to a subset of pages, e.g. form styles only get linked to a page when the page actually contains a form.
此时我会避免分成多个文件,因为它可能更难以维护。(当您打开六个 CSS 文件时,很难记住级联顺序)。但是,如果样式仅适用于页面的子集,我肯定会开始将样式移动到不同的文件,例如,表单样式仅在页面实际包含表单时才会链接到页面。