20 things to note when using CSS code in front-end practical projects

php中世界最好的语言
Release: 2018-06-13 14:02:57
Original
2375 people have browsed it

This time I bring you 20 precautions for using CSS code in front-end practical projects. The following is a practical case, let’s take a look.

01. Use margin attributes with caution

Unlike other attributes, folding will occur when margins in the vertical direction meet. This means that if one element's bottom margin meets another element's top margin, the larger of the two will be left alone. Below is a simple example.

 <p class="square red"></p>
    <p class="square blue"></p>
    .square {
        width: 80px;
        height: 80px;
    }
    .red {
        background-color: #F44336;
        margin-bottom: 40px;
    }
    .blue {
        background-color: #2196F3;
        margin-top: 30px;
    }
Copy after login

In fact, the distance between the above two elements in the vertical direction is not 70px, but 40px, and the margin of the blue square is not calculated. There are many ways to eliminate this default behavior, but the best way is to only use the margin property in one direction, such as margin-bottom.

02. Use box model layout

The box model naturally has its reasons for existence. float and inline-block certainly work, but they are basic tools for styling documents, not entire websites. In a sense, Flexbox is designed to make it easier and more precise to create the layout we want.

The Flexbox model provides a series of properties that give developers greater flexibility, and once you are familiar with them, creating any responsive layout is a piece of cake. Browser support for Flexbox is also close to perfect, so there is no reason to prevent you from using Flexbox.

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

03. Perform CSS reset

Although the situation has improved over the years, there are still many default behaviors of each browser Disagreement. The best way to solve this problem is to use a CSS reset file to reset the default styles for all elements. This allows you to work in a pure style environment and produce the same results in all browsers.

There are many libraries that do this job very well, such as normalize.css, minireset, and ress, correcting inconsistencies between browsers. If you don't want to use a library, you can also make a simple CSS reset yourself, like below.

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

This may seem harsh, but by eliminating the default margin and padding we will have an easier time placing our elements without worrying about them taking up extra space. box-sizing: border-box is a very useful property, which we will introduce below.

04. Use Border-box for all elements

Many beginners don’t know the box-sizing attribute, but it is indeed important. The best way to understand it is to look at its two optional values.

content-box(default) - When we set the width and height for the element, but those are only the dimensions of the content. All padding and borders are not included in the content, that is, outside the content.

For example, if we have a p with a width of 100px and padding of 10px, then its actual width is 120px.

border-box - padding and border are included in the width and height. If a p has a width of 100px and box-sizing: border-box is set, its width will always be 100px, no matter how much padding and border you add.

Setting border-box on all elements will help with styling, and you won’t have to do tedious math.

05. Image as background When you add an image to your site, especially if you want to do a responsive design, use a p tag and set the background attribute for it instead of using element.

It seems that the extra work does not have any effect, but in fact it is more convenient for you to style the images, maintain their original size or change according to the proportion, which requires the help of background-size, background-size There are some other properties.

 <section>
        <p>Img element</p>
        <img src="" alt="bicycle">
    </section>
    <section>
        <p>p with background image</p>
        <p></p>
    </section>
    img {
        width: 300px;
        height: 200px;
    }
    p {
        width: 300px;
        height: 200px;
        background: url('');
        background-position: center center;
        background-size: cover;
    }
    section{
        float: left;
        margin: 15px;
    }
Copy after login

One downside to this technique is that the accessibility of your page may take a slight hit because your images won’t be crawled properly by screen readers and engines. This problem can be solved by object-fit, but it is not supported by all browsers.

06. Better Table border

The table in HTML is not interesting. They are very quirky, difficult to design to be responsive, and difficult to fit in with the overall style. For example, if you want to add a top border to a table and the elements in it, you might get the following result.

正如你所见到的,它有很多重复的边框而且看起来不是很好,有一个非常快速且简单的去除双边框的方法,就是将 border-collapse: collapse 添加到 table.

这样看起来就好多了。

07、更好的注释方式

CSS 可能不是一门编程语言但它的代码仍然需要被记录,所以一些简单的注释将会对你的同事或者未来的自己很有帮助!

对于 CSS 中的一些比较大的模块,比如主要模块或者媒体查询,使用风格化的注释并且在其后留下一些空行。

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

设计中的一些细节或那些不是特别重要的模块,可以用单行注释。

 /*   Footer Buttons   */
    .footer button { }
    .footer button:hover { }
Copy after login

   另外,值得注意的是,CSS 中没有 // 注释,所以当你需要注释的时候你需要使用 /* */ 符号。

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

08、命名连接

当 class 或者 id 不止一个单词的时候,需要使用 - 符号连接,  CSS 对大小写不敏感,所以骆驼命名法不是一个好的选择。很久以前,下划线不被支持所以破折号成为了默认约定。

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

09、不要重复设置  

CSS 的许多属性值都是从 DOM 树中的上一级继承下来的,因此命名为层叠样式表。让我们以 font 为例 - 它几乎总是继承自父节点,你不需要为页面中的每一个元素设置该属性。

你只需要为 或者 设置 font 样式,然后让它一级一级流传下去就可以了。 下面是一个很好的例子。

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

当然,在任何一个子元素中你都可以按照自己的需求改变这一样式。我要说的就是能使用继承获得的属性就不要再去一一指定了。

10、CSS 动画与变换  

不要通过直接更改元素的宽度和高度去动画元素,或者是更改 left/right/top/bottom。最好的办法是使用 transform() 属性因为它提供了更加圆滑的过渡效果而且可以让你的意图在阅读代码时更加易于理解。

下面是一个例子,我们想动画一个 ball,让它往右滑动。 不要去改变 left 的值,最好是使用 translateX() 。

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

transform 以及它的所有方法(translate, rotate, scale 等)拥有几乎一致的浏览器兼容性,你可以自由使用它们。

11、不要 DIY, 使用库  

CSS 社区非常的庞大而且不断出现新的库。 库被提供于各种用途,从小片段到完善的框架,用于构建响应式程序,而且它们当中大部分都是开源的。

所以下次当你碰到 CSS 问题的时候,在你想自己动手去解决问题的时候,最好先去 Github 或者 CodePen 找找是否已经存在可用的解决方案。

12、保持选择器的特指度低  

不是所有 CSS 选择器都是生而相等的,当新手开发者书写 CSS 代码的时候通常期望它们写的选择器能够覆盖之前所有已存在的样式。 但是事情并不总像我们想的那样,就像下面这个例子:

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

我们想为所有按钮添加 .active 类使其变为红色,但这是不起作用的,因为按钮已经被一个 id 选择器设置了 background-color,而 id 选择器具有更高的特指度。它们之间的规则就像下面这样:

ID (#id) > Class (.class) > Type (比如 header)。

特指度是可以堆叠的,所以 a#button.active 的特指度是高于 a#button 的。 使用特指度高的选择器将使你不断的使用更高的去覆盖那些原本存在的选择器,这将最终导致 !important 效果。

13、不要使用 !important  

很认真的告诉你,不要使用 !important。 即时的一个快速修复在将来可能导致大量的重写。相反,找出你 CSS 选择器不工作的原因,并且尝试去修复它。

只有在一种情景中使用 !important 是可以接受的,那就是你想覆盖那些在 HTML 中定义的行内样式。而且书写行内样式也是一种非常糟糕的方式,建议停止使用。

14、使用 text-transform  

在 HTML 中,当你使用大写字母的时候可能是出于某种语义目的,比如说你想强调一个单词的重要性。

 <h3>Employees MUST wear a helmet!</h3>
Copy after login

如果出于某种目的你将一组文本都设置成大写,可以在 HTML 中正常书写文本,然后利用 CSS 转换其大小写。 它们看起来都是一样的,但是如果不在上下文中,你的内容将更有意义。  

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

这同样适用于大写或者小写的字符串 - text-transform 属性可以将它们处理的很好。

15、Em, Rem 和 Pixel  

人们在对元素和文本设置尺寸应该用 em,rem 还是 px 有很多的争论。事实是,这三者都是可行的,有自己的优点和缺点。

所有的开发者和项目都是不同的,所以不应该有什么严格的规则说明什么时候该用哪一种。下面是一些提示和良好的做法:

em - 1 em 的大小与直接父元素的字体大小有关。 通常用于媒体查询,em 对响应式设计而言是非常棒的 ,但是将每个元素的 em 值转换为 px 的比例是非常难以计算的,因为你可能要在 DOM 树上逐级跟踪元素。

rem - 以 元素中的 font-size 为基准, rem 将比例化页面中的标题和段落变得很容易。保持 中默认的 font-size 并且为其它的元素设置 rem 是一种非常棒的方法。

px - 像素是最精确的控制方式,但是在 响应式设计中它并不友好,因为它不会随屏幕大小变化而自动缩放。它们是可靠的,易于理解的,并且在值和实际结果之间呈现出良好的视觉联系。

下面我要说的是,不要害怕尝试。去使用它们并且找出哪一种是你最喜欢的。 有时候 em 和 rem 很省事,尤其对于响应式界面。

16、在大项目中使用预处理器  

你可能已经听说过它们了 - Sass, Less, PostCSS, Stylus 。预处理器是 CSS 发展的下一阶段。 它们提供的功能诸如变量, CSS 函数,选择器嵌套以及其它一些非常酷的东西。这使得 CSS 代码非常易于管理,尤其在大项目中。

举个简单的例子,下面是使用了 CSS 变量和函数的 Sass 代码片段。

$accent-color: #2196F3;
    a {
        padding: 10px 15px;
        background-color: $accent-color;
    }
    a:hover {
        background-color: darken($accent-color,10%);
    }
Copy after login

使用 CSS 预处理器的唯一缺点是,它们需要编译成真正的 CSS 代码,但是如果你已经决定在你的项目中使用一个构建脚本,那么这就不再是你应该烦恼的问题了。

17、Autoprefixers  

为各个浏览器添加前缀算得上是书写 CSS 代码最恼人的问题了。它们不一致,你永远无法精确的你需要哪一个,而且如果你真的去一个个适配并将它们都放到样式表中,你会发现这是一场噩梦。

感谢上天,有很多工具可以自动的帮你实现这一过程,甚至可以让你指定你需要支持的浏览器 :

在线工具: Autoprefixer 文本编辑器插件 - Sublime Text, Atom 库 - Autoprefixer

18、在项目中使用精简代码  

为了提高网站或app的页面加载速度我们需要总是使用精简代码 . 代码的精简版本会移除掉空白和重复的部分,这样会削减文件的大小. 当然,这样的话你的 CSS 代码将会变得非常难以阅读,所以最好总是提供一个 .min 的精简版本和一个常规的发展版本.

有很多不同的方法去精简 CSS 代码 :

在线工具 - CSS Minifier, CSS Compressor 文本编辑插件 - Sublime Text, Atom 库 - Minfiy , CSSO 和 CSSNano

Depending on your workflow, you may choose to use one of the above options, but it is recommended that you always use some way to automate this process.

19. Can I Use

Different browsers still have many inconsistent compatibility issues, use caniuse or other similar services Test whether the attribute you are using is widely supported, whether a prefix needs to be added, or whether a bug will appear on a certain platform.

Just testing whether it is still not enough, you still need to test whether the layout will happen for no reason of crashes. A good understanding of the browsers users frequently use will also be of great help, so you can see that good support is critical.

20, Validate

Validating CSS code may not be as important as validating HTML or JavaScript code, but it can still be helpful to run your code against a CSS validator, which will tell you if you have written errors or poor code. , and will even give you some pertinent suggestions to help you improve your code.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to send a POST request using JSON format

Return to the home page after mini program development and sharing page

The above is the detailed content of 20 things to note when using CSS code in front-end practical projects. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
css
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!