css编写_编写干净CSS的黄金准则-程序员宅基地

技术标签: ViewUI  css  python  java  html  javascript  

css编写

The following is an extract from our book, CSS Master, written by Tiffany Brown. Copies are sold in stores worldwide, or you can buy it in ebook form here.

以下是蒂芙尼·布朗(Tiffany Brown)所著《 CSS Master》一书的摘录。 副本在世界各地的商店中都有出售,您也可以在这里以电子书的形式购买。

编写干净CSS的黄金准则 (Golden Guidelines for Writing Clean CSS)

As mentioned, there are some rules for writing clean CSS that you should try your best to avoid breaking. They’ll help you write CSS that is lightweight and reusable:

如前所述,有一些编写干净CSS的规则,应尽量避免破坏。 它们将帮助您编写轻巧且可重复使用CSS:

  • Avoid global and element selectors

    避免使用全局和元素选择器
  • Omit overly specific selectors

    省略过于具体的选择器
  • Use semantic class names

    使用语义类名称
  • Don’t tie CSS too closely to markup structure

    不要将CSS与标记结构联系得太紧

Let’s look at these one by one.

让我们一一看一下。

避免全局选择器 (Avoid Global Selectors)

Global selectors include the universal selector (*), element selectors such as p, button, and h1, and attribute selectors such as [type=checkbox]. Style declarations applied to these selectors will be applied to every such element across the site. Here’s an example:

全局选择器包括通用选择器( * ),元素选择器(例如pbuttonh1 )以及属性选择器(例如[type=checkbox] 。 应用于这些选择器的样式声明将应用于站点中的每个此类元素。 这是一个例子:

button {
  background: #FFC107;
  border: 1px outset #FF9800;
  display: block;
  font: bold 16px / 1.5 sans-serif;
  margin: 1rem auto;
  width: 50%;
  padding: .5rem;
}

This seems innocuous enough. But what if we want to create a button that’s styled differently? Let’s style a .close button that will be used to close dialog modules:

这似乎是无害的。 但是,如果我们想创建一个样式不同的按钮怎么办? 让我们设置一个.close按钮的样式,该按钮将用于关闭对话框模块:

<section class="dialog"> 
  <button type="button" class="close">Close</button> </section>
注意:为什么不使用dialog? (Note: Why not use dialog?)

We’re using section here instead of the dialog element because support for dialog is limited to Blink-based browsers such as Chrome/Chromium, Opera, and Yandex.

我们在此使用section而不是dialog元素,因为对dialog支持仅限于基于Blink的浏览器,例如Chrome / Chromium,Opera和Yandex。

Now we need to write CSS to override every line that we don’t want to inherit from the button rule set:

现在,我们需要编写CSS来覆盖我们不想从button规则集中继承的每一行:

.close {
  background: #e00;
  border: 2px solid #fff;
  color: #fff;
  display: inline-block;
  margin: 0;
  font-size: 12px;
  font-weight: normal;
  line-height: 1;
  padding: 5px;
  border-radius: 100px;
  width: auto;        
}

We’d still need many of these declarations to override browser defaults. But what if we scope our button styles to a .default class instead? We can then drop the display, font-weight, line-height, margin, padding, and width declarations from our .close rule set. That’s a 23% reduction in size:

我们仍然需要许多这些声明来覆盖浏览器的默认设置。 但是,如果我们将button样式的范围改为.default类,该怎么办? 然后,我们可以从.close规则集中删除displayfont-weightline-heightmarginpaddingwidth声明。 大小减少了23%:

.default {
  background: #FFC107;
  border: 1px outset #FF9800;
  display: block;
  font: bold 16px / 1.5 sans-serif;
  margin: 1rem auto;
  width: 50%;
  padding: .5rem;
}

.close {
  background: #e00;
  border: 2px solid #fff;
  color: #fff;
  font-size: 12px;
  padding: 5px;
  border-radius: 100px;
}

Just as importantly, avoiding global selectors reduces the risk of styling conflicts. A developer working on one module or document won’t inadvertently add a rule that creates a side effect in another module or document.

同样重要的是,避免使用全局选择器可以减少样式冲突的风险。 在一个模块或文档上工作的开发人员不会无意中添加一条规则,该规则会在另一模块或文档中产生副作用。

Global styles and selectors are perfectly okay for resetting and normalizing default browser styles. In most other cases, however, they invite bloat.

全局样式和选择器完全可以用于重置和规范化默认浏览器样式。 但是,在大多数其他情况下,它们会引起膨胀。

避免选择过多的选择器 (Avoid Overly Specific Selectors)

Maintaining low specificity in your selectors is one of the keys to creating lightweight, reusable, and maintainable CSS. As you may recall on specificity, a type selector has the specificity 0,0,1. Class selectors, on the other hand, have a specificity of 0,1,0:

在选择器中保持低特异性是创建轻量级,可重用和可维护CSS的关键之一。 您可能还记得特异性,类型选择器的特异性为0,0,1。 另一方面,类选择器的特异性为0,1,0:

/* Specificity of 0,0,1 */
p {
  color: #222;
  font-size: 12px;
}

/* Specificity of 0,1,0 */
.error {
  color: #a00;
}

When you add a class name to an element, the rules for that selector take precedence over more generic-type selector rules. There’s no need to further qualify a class selector by combining it with a type selector. Doing so increases the specificity of that selector and increases the overall file size.

将类名称添加到元素时,该选择器的规则优先于更多的泛型选择器规则。 无需通过将类型选择器与类型选择器结合来进一步限定类选择器。 这样做会增加选择器的特异性,并增加整个文件的大小。

Put differently, using p.error is unnecessarily specific because .error achieves the same goal. Another advantage is that .error can be reused with other elements. A p.error selector limits the .error class to p elements.

换句话说,使用p.error是不必要的特定,因为.error可以达到相同的目标。 另一个优点是.error可以与其他元素一起重用。 p.error选择器将.error类限制为p元素。

不要上课 (Don’t Chain Classes)

Also avoid chaining class selectors. Selectors such as .message.warning have a specificity of 0,2,0. Higher specificity means they’re hard to override, plus chaining often causes side effects. Here’s an example:

还要避免链接类选择器。 .message.warning选择器的特异性为0,2,0。 更高的特异性意味着它们很难被覆盖,而且连锁往往会带来副作用。 这是一个例子:

message {
  background: #eee;
  border: 2px solid #333;
  border-radius: 1em;
  padding: 1em;
}
.message.error {
  background: #f30;
  color: #fff;
}
.error {
  background: #ff0;
  border-color: #fc0;
}

Using <p class="message"> with this CSS gives us a nice gray box with a dark gray border, as seen in Figure 2.1:

在此CSS上使用<p class="message">可以为我们提供一个带有深灰色边框的漂亮灰色框,如图2.1所示:

alt

Figure 2.1. The visual effect of our .message selector

图2.1。 .message选择器的视觉效果

Using <p class="message error">, however, gives us the background of .message.error and the border of .error shown in Figure 2.2:

但是,使用<p class="message error">为我们提供.message.error的背景和图2.2所示的.error边框:

alt

Figure 2.2. The visual result of using .message.error as a selector

图2.2。 使用.message.error作为选择器的视觉结果

The only way to override a chained class selector would be to use an even more specific selector. To be rid of the yellow border, we’d need to add a class name or type selector to the chain: .message.warning.exception or div.message.warning. It’s more expedient to create a new class instead. If you do find yourself chaining selectors, go back to the drawing board. Either the design has inconsistencies, or you’re chaining prematurely in an attempt to prevent problems that you don’t have. Fix those problems. The maintenance headaches you’ll prevent and the reusability you’ll gain are worth it.

覆盖链接的类选择器的唯一方法是使用更具体的选择器。 要消除黄色边框,我们需要在链中添加类名或类型选择器: .message.warning.exceptiondiv.message.warning 。 代替创建一个新类是更方便的。 如果发现自己链接了选择器,请返回至绘图板。 设计有不一致之处,或者您过早地进行了链结,以防止出现您没有的问题。 解决这些问题。 您可以避免的维护难题和可重用性值得。

避免使用id选择器 (Avoid Using id Selectors)

Because you can only have one element per id per document, rule sets that use id selectors are hard to repurpose. Doing so typically involves using a list of id selectors; for example, #sidebar-features and #sidebar-sports.

由于每个文档的每个id只能包含一个元素,因此使用id选择器的规则集很难重新利用。 这样做通常涉及使用id选择器列表; 例如#sidebar-features#sidebar-sports

Identifiers also have a high degree of specificity, so we’ll need longer selectors to override declarations. In the CSS that follows, we need to use #sidebar.sports and #sidebar.local to override the background color of #sidebar:

标识符也具有高度的特异性,因此我们需要更长的选择器来覆盖声明。 在随后CSS中,我们需要使用#sidebar.sports#sidebar.local覆盖#sidebar的背景色:

#sidebar {
  float: right;
  width: 25%;
  background: #eee;
}
#sidebar.sports  {
  background: #d5e3ff;
}
#sidebar.local {
  background: #ffcccc;
}

Switching to a class selector, such as .sidebar, lets us simplify our selector chain:

切换到类选择器,例如.sidebar ,可以简化选择器链:

sidebar {
  float: right;
  width: 25%;
  background: #eee;
}
.sports  {
  background: #d5e3ff;
}
.local {
  background: #ffcccc;
}

As well as saving us a few bytes, our .sports, and .local rule sets can now be added to other elements.

除了为我们节省一些字节.sports ,现在还可以将.sports.local规则集添加到其他元素。

Using an attribute selector such as [id=sidebar] lets us get around the higher specificity of an identifier. Though it lacks the reusability of a class selector, the low specificity means that we can avoid chaining selectors.

使用诸如[id=sidebar]类的属性选择器可使我们避开标识符的更高特异性。 尽管它缺乏类选择器的可重用性,但较低的特异性意味着我们可以避免链接选择器。

注意:当id选择器的高特异性有用时 (Note: When the High Specificity of id Selectors is Useful)

In some circumstances, you might want the higher specificity of an id selector. For example, a network of media sites might wish to use the same navigation bar across all of its web properties. This component must be consistent across sites in the network, and should be hard to restyle. Using an id selector reduces the chances of those styles being accidentally overridden.

在某些情况下,您可能希望 id选择器具有更高的特异性。 例如,媒体站点网络可能希望在其所有Web属性中使用相同的导航栏。 该组件必须在网络中的各个站点之间保持一致,并且应该很难重新设置样式。 使用id选择器可减少意外覆盖这些样式的机会。

Finally, let’s talk about selectors such as #main article.sports table#stats tr:nth-child(even) td:last-child. Not only is it absurdly long, but with a specificity of 2,3,4, it’s also not reusable. How many possible instances of this selector can there be in your markup? Let’s make this better. We can immediately trim our selector to #stats tr:nth-child(even) td:last-child. It’s specific enough to do the job. Yet the far better approach—for both reusability and to minimize the number of bytes—is to use a class name instead.

最后,让我们讨论一下诸如#main article.sports table#stats tr:nth-child(even) td:last-child 。 它不仅长得荒唐,而且具有2,3,4的特异性,也无法重用。 有多少可能的情况下,这种选择可以有在您的标记? 让我们做得更好。 我们可以立即将选择器调整为#stats tr:nth-child(even) td:last-child 。 它足够具体地完成这项工作。 然而,更好的方法(可重用性和最大程度减少字节数)是使用类名。

注意:预处理器嵌套的症状 (Note: A Symptom of Preprocessor Nesting)

Overly specific selectors are often the result of too much preprocessor nesting.

选择器过于具体通常是过多的预处理器嵌套的结果。

使用语义类名称 (Use Semantic Class Names)

When we use the word semantic, we mean meaningful. Class names should describe what the rule does or the type of content it affects. We also want names that will endure changes in the design requirements. Naming is harder than it looks.

当我们使用语义一词时,我们的意思是有意义的 。 类名应描述规则的作用或影响的内容类型。 我们还希望名称能够承受设计要求的变化。 命名比看起来难。

Here are examples of what not to do: .red-text, .blue-button, .border-4px, .margin10px. What’s wrong with these? They are too tightly coupled to the existing design choices. Using class="red-text" to mark up an error message does work. But what happens if the design changes and error messages become black text inside orange boxes? Now your class name is inaccurate, making it tougher for you and your colleagues to understand what’s happening in the code.

以下是不执行操作的示例: .blue-button .red-text.blue-button.border-4px.margin10px 。 这些怎么了 它们与现有的设计选择紧密结合在一起。 使用class="red-text"标记错误消息确实可行。 但是,如果设计更改并且错误消息变为橙色框内的黑色文本,会发生什么? 现在您的类名不正确,这使您和您的同事很难理解代码中正在发生的事情。

A better choice in this case is to use a class name such as .alert, .error, or .message-error. These names indicate how the class should be used and the kind of content (error messages) that they affect. For class names that define page layout, add a prefix such as layout-, grid-, col-, or simply l- to indicate at a glance what it is they do. The section on BEM methodology later on describes a process for this.

在这种情况下,更好的选择是使用类名称,例如.alert.error.message-error 。 这些名称指示应如何使用该类以及它们影响的内容(错误消息)的种类。 对于定义页面布局的类名称,添加诸如layout-grid-col-或简单地l-类的前缀,以一眼就表明它们的作用。 稍后有关BEM方法论的部分介绍了此过程。

避免将CSS与标记紧密联系在一起 (Avoid Tying CSS Closely to Markup)

You’ve probably used child or descendant selectors in your code. Child selectors follow the pattern E > F where F is an element, and E is its immediate parent. For example, article > h1 affects the h1 element in <article><h1>Advanced CSS</h1></article>, but not the h1 element in <article><section><h1>Advanced CSS</h1></section></article>. A descendant selector, on the other hand, follows the pattern E F where F is an element, and E is an ancestor. To use our previous example, article h1 selects the h1 element in both cases.

您可能在代码中使用了子选择器或子代选择器。 子选择器遵循模式E > F ,其中F是元素,E是其直接父元素。 例如, article > h1影响h1在元件<article><h1>Advanced CSS</h1></article> ,而不是h1中元素<article><section><h1>Advanced CSS</h1></section></article> 。 另一方面,后代选择器遵循模式EF ,其中F是元素,E是祖先。 为了使用前面的示例, article h1在两种情况下都选择了h1元素。

Neither child nor descendant selectors are inherently bad. In fact, they work well to limit the scope of CSS rules. But they’re far from ideal, however, because markup occasionally changes.

子选择器和子代选择器本质上都不是坏的。 实际上,它们很好地限制了CSS规则的范围。 但是它们并不理想,因为标记偶尔会发生变化。

Raise your hand if you’ve ever experienced the following. You’ve developed some templates for a client and your CSS uses child and descendant selectors in several places. Most of those children and descendants are also element selectors, so selectors such as .promo > h2 and .media h3 are all over your code. Your client also hired an SEO consultant, who reviewed your markup and suggested you change your h2 and h3 elements to h1 and h2 elements. The problem is that we also have to change our CSS.

如果您曾经经历过以下活动,请举手。 您已经为客户端开发了一些模板,并且CSS在多个位置使用了子选择器和子代选择器。 这些子代和后代中的大多数也是元素选择器,因此.promo > h2.media h3类的选择器遍布您的代码。 您的客户还雇用了SEO顾问,该顾问检查了您的标记并建议您将h2h3元素更改为h1h2元素。 问题在于我们还必须更改CSS。

Once again, class selectors reveal their advantage. Using .promo > .headline or .media .title (or more simply .promo-headline and .media-title) lets us change our markup without having to change our CSS.

再次,类选择器展示了它们的优势。 使用.promo > .headline.media .title (或更简单地说是.promo-headline.media-title ),我们无需更改CSS就可以更改标记。

Of course, this rule assumes that you have access to and control over the markup. This may not be true if you’re dealing with a legacy CMS. It’s appropriate and necessary to use child, descendant, or pseudo-class selectors in such cases.

当然,此规则假定您有权访问和控制标记。 如果您要处理旧版CMS,则可能不是这样。 在这种情况下,使用子级,子级或伪类选择器是适当且必要的。

注意:更合理CSS规则 (Note: More Architecturally Sound CSS Rules)

Philip Walton discusses these and other these rules in his article “CSS Architecture.” I also recommend Harry Roberts’ site CSS Guidelines and Nicolas Gallagher’s post About HTML Semantics and Front-end Architecture for more thoughts on CSS architecture.

Philip Walton在他的文章“ CSS Architecture”中讨论了这些规则和其他规则 我还建议Harry Harrys的站点CSS Guidelines和Nicolas Gallagher的帖子About HTML Semantics and Front-end Architecture有关CSS架构的更多想法。

We’ll now look at two methodologies for CSS architecture. Both methods were created to improve the development process for large sites and large teams; however, they work just as well for teams of one.

现在,我们将讨论CSS体系结构的两种方法。 创建这两种方法都是为了改善大型站点和大型团队的开发过程。 但是,对于一个团队来说,它们也同样有效。

翻译自: https://www.sitepoint.com/golden-guidelines-for-writing-clean-css/

css编写

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/culi4814/article/details/108377527

智能推荐

oracle 12c 集群安装后的检查_12c查看crs状态-程序员宅基地

文章浏览阅读1.6k次。安装配置gi、安装数据库软件、dbca建库见下:http://blog.csdn.net/kadwf123/article/details/784299611、检查集群节点及状态:[root@rac2 ~]# olsnodes -srac1 Activerac2 Activerac3 Activerac4 Active[root@rac2 ~]_12c查看crs状态

解决jupyter notebook无法找到虚拟环境的问题_jupyter没有pytorch环境-程序员宅基地

文章浏览阅读1.3w次,点赞45次,收藏99次。我个人用的是anaconda3的一个python集成环境,自带jupyter notebook,但在我打开jupyter notebook界面后,却找不到对应的虚拟环境,原来是jupyter notebook只是通用于下载anaconda时自带的环境,其他环境要想使用必须手动下载一些库:1.首先进入到自己创建的虚拟环境(pytorch是虚拟环境的名字)activate pytorch2.在该环境下下载这个库conda install ipykernelconda install nb__jupyter没有pytorch环境

国内安装scoop的保姆教程_scoop-cn-程序员宅基地

文章浏览阅读5.2k次,点赞19次,收藏28次。选择scoop纯属意外,也是无奈,因为电脑用户被锁了管理员权限,所有exe安装程序都无法安装,只可以用绿色软件,最后被我发现scoop,省去了到处下载XXX绿色版的烦恼,当然scoop里需要管理员权限的软件也跟我无缘了(譬如everything)。推荐添加dorado这个bucket镜像,里面很多中文软件,但是部分国外的软件下载地址在github,可能无法下载。以上两个是官方bucket的国内镜像,所有软件建议优先从这里下载。上面可以看到很多bucket以及软件数。如果官网登陆不了可以试一下以下方式。_scoop-cn

Element ui colorpicker在Vue中的使用_vue el-color-picker-程序员宅基地

文章浏览阅读4.5k次,点赞2次,收藏3次。首先要有一个color-picker组件 <el-color-picker v-model="headcolor"></el-color-picker>在data里面data() { return {headcolor: ’ #278add ’ //这里可以选择一个默认的颜色} }然后在你想要改变颜色的地方用v-bind绑定就好了,例如:这里的:sty..._vue el-color-picker

迅为iTOP-4412精英版之烧写内核移植后的镜像_exynos 4412 刷机-程序员宅基地

文章浏览阅读640次。基于芯片日益增长的问题,所以内核开发者们引入了新的方法,就是在内核中只保留函数,而数据则不包含,由用户(应用程序员)自己把数据按照规定的格式编写,并放在约定的地方,为了不占用过多的内存,还要求数据以根精简的方式编写。boot启动时,传参给内核,告诉内核设备树文件和kernel的位置,内核启动时根据地址去找到设备树文件,再利用专用的编译器去反编译dtb文件,将dtb还原成数据结构,以供驱动的函数去调用。firmware是三星的一个固件的设备信息,因为找不到固件,所以内核启动不成功。_exynos 4412 刷机

Linux系统配置jdk_linux配置jdk-程序员宅基地

文章浏览阅读2w次,点赞24次,收藏42次。Linux系统配置jdkLinux学习教程,Linux入门教程(超详细)_linux配置jdk

随便推点

matlab(4):特殊符号的输入_matlab微米怎么输入-程序员宅基地

文章浏览阅读3.3k次,点赞5次,收藏19次。xlabel('\delta');ylabel('AUC');具体符号的对照表参照下图:_matlab微米怎么输入

C语言程序设计-文件(打开与关闭、顺序、二进制读写)-程序员宅基地

文章浏览阅读119次。顺序读写指的是按照文件中数据的顺序进行读取或写入。对于文本文件,可以使用fgets、fputs、fscanf、fprintf等函数进行顺序读写。在C语言中,对文件的操作通常涉及文件的打开、读写以及关闭。文件的打开使用fopen函数,而关闭则使用fclose函数。在C语言中,可以使用fread和fwrite函数进行二进制读写。‍ Biaoge 于2024-03-09 23:51发布 阅读量:7 ️文章类型:【 C语言程序设计 】在C语言中,用于打开文件的函数是____,用于关闭文件的函数是____。

Touchdesigner自学笔记之三_touchdesigner怎么让一个模型跟着鼠标移动-程序员宅基地

文章浏览阅读3.4k次,点赞2次,收藏13次。跟随鼠标移动的粒子以grid(SOP)为partical(SOP)的资源模板,调整后连接【Geo组合+point spirit(MAT)】,在连接【feedback组合】适当调整。影响粒子动态的节点【metaball(SOP)+force(SOP)】添加mouse in(CHOP)鼠标位置到metaball的坐标,实现鼠标影响。..._touchdesigner怎么让一个模型跟着鼠标移动

【附源码】基于java的校园停车场管理系统的设计与实现61m0e9计算机毕设SSM_基于java技术的停车场管理系统实现与设计-程序员宅基地

文章浏览阅读178次。项目运行环境配置:Jdk1.8 + Tomcat7.0 + Mysql + HBuilderX(Webstorm也行)+ Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)。项目技术:Springboot + mybatis + Maven +mysql5.7或8.0+html+css+js等等组成,B/S模式 + Maven管理等等。环境需要1.运行环境:最好是java jdk 1.8,我们在这个平台上运行的。其他版本理论上也可以。_基于java技术的停车场管理系统实现与设计

Android系统播放器MediaPlayer源码分析_android多媒体播放源码分析 时序图-程序员宅基地

文章浏览阅读3.5k次。前言对于MediaPlayer播放器的源码分析内容相对来说比较多,会从Java-&amp;amp;gt;Jni-&amp;amp;gt;C/C++慢慢分析,后面会慢慢更新。另外,博客只作为自己学习记录的一种方式,对于其他的不过多的评论。MediaPlayerDemopublic class MainActivity extends AppCompatActivity implements SurfaceHolder.Cal..._android多媒体播放源码分析 时序图

java 数据结构与算法 ——快速排序法-程序员宅基地

文章浏览阅读2.4k次,点赞41次,收藏13次。java 数据结构与算法 ——快速排序法_快速排序法