Home  >  Article  >  Web Front-end  >  20 Tips for Writing Modern CSS Code

20 Tips for Writing Modern CSS Code

黄舟
黄舟Original
2017-01-18 13:09:571025browse

CSS Cascading Style Sheet

CSS (Cascading Style Sheet) is a cascading style sheet. It is a computer language used to represent document styles such as HTML (an application of Standard Generalized Markup Language) or XML (a subset of Standard Generalized Markup Language).


Understand what Margin Collapse is

Unlike many other properties, the vertical margins in the box model will collapse when they meet, that is to say, when When the bottom margin of an element is adjacent to the top margin of another element, only the larger value of the two will be retained. You can learn from the following simple example:

.square {    width: 80px;    height: 80px;
}.red {    background-color: #F44336;    margin-bottom: 40px;
}.blue {    background-color: #2196F3;    margin-top: 30px;
}

In the above example We will find that the margins of the red and blue squares do not add up to get 70px, but only the red lower margin is retained. We can use some methods to avoid this behavior, but it is recommended to use the margin-bottom attribute as uniformly as possible, so that it appears more harmonious.

Use Flexbox for layout

In traditional layout we are used to using Floats or inline-blocks, but they are more suitable for formatting documents rather than entire websites. Flexbox is a specialized tool for layout. The Flexbox model allows developers to use many convenient and extensible attributes for layout. It is estimated that once you use it, you will not let it go:

.container {    display: flex;    /* Don't forget to add prefixes for Safari */display: -webkit-flex;
}

We have provided a lot of introductions and tips about Flexbox on Tutorialzine, such as 5 Flexbox Techniques You Need to Know About.

Using CSS Reset

Although with the rapid development of browsers and the unification of specifications over the years, the fragmentation of browser features has improved, but there are still differences between different browsers There are a lot of behavioral differences. The best way to solve this problem is to use a CSS Reset to set a unified style for all elements, ensuring that you can start working on the basis of a relatively unified and clean style sheet. Currently popular Reset libraries include normalize.css, minireset and ress, which can correct many known differences between browsers. And if you don’t plan to use an external library, it is recommended to use the following basic rules:

* {    margin: 0;    padding: 0;    box-sizing: border-box;
}

The above rules seem useless, but if different browsers provide you with Setting different default values ​​for margins/padding can still be quite troublesome.

Everything should be Border-box

Although many beginners do not understand the box-sizing attribute, it is indeed quite important. The best way to understand it is to look at its two values:

The default value is content-box, that is, when we set the height/width attribute of an element, it will only affect it Content size. All padding and sides are accumulated on top of it. For example, if a

tag is set to width 100 and padding 10, then the final element will occupy 120 (100 + 2*10) pixels.

border-box: The padding and sides are included in width/height. For example, a

with width: 100px is set, no matter how much its padding or side length is set, its occupancy The sizes are all 100px.

Setting the element to border-box will be very convenient for you to style and layout. In this way, you can set height and width restrictions on the parent element without worrying about the padding or sides of the child elements breaking this restriction.

Use Images as background image

如果需要在响应式的环境下展示图片,有个简单的小技巧就是使用该图片作为某个

的背景图而不是直接使用img标签。基于这种方式配合上background-size与background-position这两个属性,可以很方便地按比例缩放:
img {    width: 300px;    height: 200px;
}div {    width: 300px;    height: 200px;    
background: url('http://cdn.tutorialzine.com/wp-content/uploads/2016/08/bicycle.jpg');    
background-position: center center;    background-size: cover;
}section{    float: left;    margin: 15px;
}

不过这种方式也是存在缺陷的,譬如你无法设置图片的懒加载、图片无法被搜索引擎或者其他类似的工具抓取到,有个不错的属性叫object-fit可以解决这个问题,不过该属性目前的浏览器支持并不是很完善。

Better Table Borders

HTML中使用Tables进行布局一直是个很头疼的问题,它们使用起来很简单,但是无法进行响应式操作,并且也不方便进行全局样式设置。譬如,如果你打算为Table的边与单元的边添加样式,可能得到的结果如下:

table {    width: 600px;    border: 1px solid #505050;    margin-bottom: 15px;    color:#505050;
}td{    border: 1px solid #505050;    padding: 10px;
}

20 Tips for Writing Modern CSS Code

这里存在的问题是出现了很多的重复的边,会导致视觉上不协调的情况,那么我们可以通过设置border-collapse:collapse来进行处理:

20 Tips for Writing Modern CSS Code

注释格式优化

CSS虽然谈不上一门编程语言但是其仍然需要添加注释以保障整体代码的可读性,只要添加些简单的注释不仅可以方便你更好地组织整个样式表还能够让你的同事或者未来的自己更好地理解。对于CSS中整块的注释或者使用在Media-Query中的注释,建议是使用如下形式:

/*---------------
    #Header
---------------*/header { }header nav { }/*---------------
    #Slideshow
---------------*/.slideshow { }

而设计的细节说明或者一些不重要的组件可以用如下单行注释的方式:

/*   Footer Buttons   */.footer button { }.footer button:hover { }

同时,不要忘了CSS中是没有//这种注释方式的:

/*  Do  */p {
    padding: 15px;    /*border: 1px solid #222;*/}/*  Don't  */p {
    padding: 15px;    // border: 1px solid #222;  }

使用Kebab-case命名变量

对于样式类名或者ID名的命名都需要在多个单词之间添加-符号,CSS本身是大小写不敏感的因此你是用不了camelCase的,另一方面,很久之前也不支持下划线,所以现在的默认的命名方式就是使用-:

/*  Do     */.footer-column-left { }/*  Don't  */.footerColumnLeft { }.footer_column_left { }

而涉及到具体的变量命名规范时,建议是使用BEM规范,只要遵循一些简单的原则即可以保证基于组件风格的命名一致性。你也可以参考CSS Tricks来获得更多的细节描述。

避免重复代码

大部分元素的CSS属性都是从DOM树根部继承而来,这也是其命名为级联样式表的由来。我们以font属性为例,该属性往往是继承自父属性,因此我们并不需要再单独地为元素设置该属性。我们只需要在html或者body中添加该属性然后使其层次传递下去即可:

html {    font: normal 16px/1.4 sans-serif;
}

使用transform添加CSS Animations

不建议直接改变元素的width与height属性或者left/top/bottom/right这些属性来达到动画效果,而应该优先使用transform()属性来提供更平滑的变换效果,并且能使得代码的可读性会更好:

.ball {    left: 50px;    transition: 0.4s ease-out;
}/* Not Cool*/.ball.slide-out {    left: 500px;
}/* Cool*/.ball.slide-out {    transform: translateX(450px);
}

Transform的几个属性translate、rotate、scale都具有比较好的浏览器兼容性可以放心使用。

不要重复造轮子

现在CSS社区已经非常庞大,并且不断地有新的各式各样的库开源出来。这些库可以帮助我们解决从小的代码片到用于构建完整的响应式应用的全框架。所以如果下次你再碰到什么CSS问题的时候,在打算撸起袖子自己上之前可以尝试在GitHUB或者CodePen上搜索可行方案。

尽可能使用低优先级的选择器

并不是所有的CSS选择器的优先级都一样,很多初学者在使用CSS选择器的时候都是考虑以新的特性去复写全部的继承特性,不过这一点在某个元素多状态时就麻烦了,譬如下面这个例子:

a{    color: #fff;    padding: 15px;
}a#blue-btn {    background-color: blue;
}a.active {    background-color: red;
}

我们本来希望将.active类添加到按钮上然后使其显示为红色,不过在上面这个例子中很明显起不了作用,因为button已经以ID选择器设置过了背景色,也就是所谓的Higher Selector Specificity。一般来说,选择器的优先级顺序为:ID(#id) > Class(.class) > Type(header)

避免使用!important

认真的说,千万要避免使用!important,这可能会导致你在未来的开发中无尽的属性重写,你应该选择更合适的CSS选择器。而唯一的可以使用!important属性的场景就是当你想去复写某些行内样式的时候,不过行内样式本身也是需要避免的。

使用text-transform属性设置文本大写

<div class="movie-poster">Star Wars: The Force Awakens</div>.movie-poster {
    text-transform: uppercase;
}

Em, Rem, 以及 Pixel

已经有很多关于人们应该如何使用em,rem,以及px作为元素尺寸与文本尺寸的讨论,而笔者认为,这三个尺寸单位都有其适用与不适用的地方。不同的开发与项目都有其特定的设置,因此并没有通用的规则来决定应该使用哪个单位,这里是我总结的几个考虑:

em – 其基本单位即为当前元素的font-size值,经常适用于media-queries中,em是特别适用于响应式开发中。

rem – 其是相对于html属性的单位,可以保证文本段落真正的响应式尺寸特性。

px – Pixels 并没有任何的动态扩展性,它们往往用于描述绝对单位,并且可以在设置值与最终的显示效果之间保留一定的一致性。

在大型项目中使用预处理器

估计你肯定听说过 Sass, Less, PostCSS, Stylus这些预处理器与对应的语法。Preprocessors可以允许我们将未来的CSS特性应用在当前的代码开发中,譬如变量支持、函数、嵌套式的选择器以及很多其他的特性,这里我们以Sass为例:

$accent-color: #2196F3;a {
    padding: 10px 15px;
    background-color: $accent-color;
}

a:hover {
    background-color: darken($accent-color,10%);
}

使用Autoprefixers来提升浏览器兼容性

使用特定的浏览器前缀是CSS开发中常见的工作之一,不同的浏览器、不同的属性对于前缀的要求也不一样,这就使得我们无法在编码过程中记住所有的前缀规则。并且在写样式代码的时候还需要加上特定的浏览器前缀支持也是个麻烦活,幸亏现在也是有很多工具可以辅助我们进行这样的开发:

Online tools: Autoprefixer

Text editor plugins: Sublime Text, Atom

Libraries: Autoprefixer (PostCSS)

Use Minified code in the production environment

In order to improve the loading speed of the page, we should use the compressed resource code by default in the production environment. During the compression process, all blanks and repetitions will be removed to reduce the size of the entire file. Of course, the compressed code is unreadable, so we should still use the normal version during the development phase. There are many current tools for CSS compression:

Online tools – CSS Minifier (API included), CSS Compressor

Text editor plugins: Sublime Text, Atom

Libraries: Minfiy (PHP), CSSO and CSSNano (PostCSS, Grunt, Gulp)

Which tool you choose must depend on your own workflow~

See Caniuse

Different browsers vary greatly in compatibility, so if we can target the browser we need to adapt to, we can query the browser version compatibility of a certain feature on caniuse, whether we need to add a specific prefix or Are there bugs on a certain platform, etc. However, it is definitely not enough to use caniuse. We also need to use some additional services for detection.

Validate: Verification

The verification of CSS may not be as important as HTML verification or JavaScript verification, but it is still good to use the Lint tool to verify your CSS code before official release. Very meaningful. It will tell you about potential errors in your code, prompt you about some code that does not meet best practices, and give you some suggestions to improve the performance of your code. Just like Minifers and Autoprefixers, there are many tools available:

Online tools: W3 Validator, CSS Lint

Text editor plugins: Sublime Text, Atom

Libraries: lint ( Node.js, PostCSS), css-validator (Node.js)


The above are 20 suggestions for writing modern CSS code. For more related content, please pay attention to PHP Chinese website (m.sbmmt.com)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn