search
HomeWeb Front-endCSS TutorialSome tips for writing css

Some tips for writing css

Jan 23, 2017 pm 03:08 PM
css

Javascripty has embarked on the road of engineering. Various mvm and mvvm frameworks have been dizzying. We will not discuss js here. Let me talk about some of my experience in writing CSS in actual work. Of course, many people have also summarized this experience. What I am talking about is definitely not as good as those written by some big names. I just simply bring out my work experience and compare it with Share it with everyone.

If you want to do your job well, you must first sharpen your tools

When writing CSS, you need to master at least one development tool, whether it is SASS, It's still LESS, essentially they are the same, but the syntax is a little different. If you are still writing CSS by hand, please learn about them as soon as possible, and choose one of them according to your own habits and use them. Personally, I prefer sass, which is more in line with my writing habits. There are also many people who like Less. They think the less syntax is more convenient.

What SASS/LESS

SASS (LESS) is an extension of CSS3, adding rule nesting, variables, mixing, selector inheritance, etc. Convert it into standard, well-formed CSS code by using command line tools or WEB framework plug-ins.

Why do we need SASS/LESS

As a development tool, they provide many convenient writing methods, which greatly saves designers’ time and makes CSS development easier. Be simple and maintainable.
They are also the cornerstone of writing modular, maintainable CSS.

How to use

There are a lot of tutorials about SASS/LESS on the Internet, so I won’t waste space on the basic syntax here.
You can search online by yourself. They are all similar. Once you learn one, you can basically use it:

I use SASS as an example for the following content. The content is not limited to SASS, LESS is also applicable!

God said, there is no rule without rules

Yes, there is no rule without rules. You need to understand a css naming standard or make your own standard (it is not recommended to do it yourself) Definition, not conducive to teamwork);

Why is there a need for a naming convention?

When you have written a lot of CSS, you will find that there is no effective naming convention and it will make you miserable. This feeling is especially noticeable if you are working on a slightly larger project, or in the process of developing it in collaboration with others. Because when you name the css, you will find that the name is used elsewhere, or a teammate has already used it, and you must rename it. Over time, the naming of CSS will become messy, smelly and long, and it is impossible to guess the meaning of the naming at a glance.

BEM naming convention

Various naming conventions are different, and the wise have their own opinions. Here I will introduce the BEM naming convention. What I introduce may not be suitable for you. , you need to think about which naming convention suits you. .

BEM is a CSS Class naming method proposed by the Yandex team, aiming to better create CSS/Sass modules.

BEM means block, element, and modifier.

●block: can be understood as a region, a component or a block-level element. The specific distinction needs to be analyzed based on the actual situation;

●block__element: It is an element in the above block , for example, if there is an a tag (a: element) in the navigation (nav: block), it is an element. Block and element are linked by two underscores;

●block__element–modifier: My understanding is state or attribute. For example, the a tag in element has three states: active, hover, and normal. These three states are modifiers. The midifier is connected by two "-" horizontal lines.

For the example mentioned above, I will use the actual code to demonstrate:

<!-- HTML结构 --><nav class="nav">
  <a href="#" class="nav__item nav__item--active">当前页:active</a>
  <a href="#" class="nav__item nav__item--hover">假设鼠标在这里要加个hover的class</a>
  <a href="#" class="nav__item nav__item--normal">假设需要加个normar的状态</a></nav>
// SASS写法.nav{
  &__item{
    &--active{
      <!-- active样式 -->
    }
    &--hover{
      <!-- hover样式 -->
    }
    &--normal{
      <!-- normal样式 -->
    }
  }}
/* 编译后的css */
.nav{ }
.nav__item{ }
.nav__item--active{ }
.nav__item--hover{ }
.nav__item--normal{ }

From the above example, you can see the css at a glance Meaning, and the compiled css does not have any nesting, but the structure of SASS is very clear and can be seen at a glance.

It can be seen that using SASS and BEM can write a code that is easy to read, maintainable, and modular;

God said, I don’t know you

A readable SASS must have a description. Every file and function needs a description.

For a SASS file, you need to explain at least two points, whether the SASS is public or private, which page and which part

@charset "utf-8"/** 预定义函数* author:xxx* time:xxxx-xx-xx*//** 清除浮动* use: @include clearfix();* author: xxx* time: xxxx-xx-xx*/@mixin clearfix(){
  *zoom: 1;
  &:before,
  &:after {
      content: "";
      display: table;
  }
  &:after {
      clear: both;
      overflow: hidden;
  }}

God said the world must be unified

●reset

css reset is essential. There are many css reset codes on the Internet. Compass also has a reset module. You only need to @import "compass/reset". If you think these codes are too redundant, you need to at least ensure that your css has margin and padding reset, so that you can ensure that the css has the same style in each browser.

*{
  margin: 0;
  padding: 0;}

●Space/Line Spacing/Margin

●Font Size

●Color

●Level

●Height

......

Why variables are needed


Using a separate variable has many benefits. The biggest one is maintainability. Sex, who knows who uses it!

Maintainability

●When you finish the development, take it to the designer for acceptance. The designer says this is not good, so change the color! ——It’s okay, I’ll change the variable!

●产品说,这里不好,列表间距太大了,小屏幕只显示那么一点点!—— 没事,我改个变量!

●来来来,产品说我们换一套皮肤! —— 没事,我重新定义一份变量!

……

这些例子可以让你明白有一份variables是多么重要了吧。其实这些只是在可维护方面的好处。作为一名前端,我们是最接近用户的工程师,我们不能仅仅停留在代码层面,更需要的是站在用户体验的角度思考问题,而variables可以让我们有一套规范,确保页面一致性

一致性

FE是面向用户的,我们需要对用户负责。设计师在设计页面的时候,不能所有的像素的都很精确,不可能每次的颜色都是毫无差错的。所以在这时候,就需要规范了,如果设计师没有规范,那我们自己制定一套规范。例如:

●同一个项目,一个页面的列表高度是20px,另一个页面的列表是21px,这时我们无需理会,直接使用我们之前定义的列表高度进行开发。

●同一个页面,有两个error的颜色#dc4c4c和#d84a4a,我们也无需理会,使用统一的error颜色变量;

这些是用户体验的细节,通过一份variables可以让我们保持页面的一致性。
这里只是略微提下用户体验,之后我再写一篇《前端工程师必须重视的用户体验》来详细讲解下用户体验。

module(模块化,基于SASS/LESS)

模块化在js中经常听到,对于css来说,模块化对于易读性和可维护性同样重要。那么如何来做模块化呢?

多文件夹

建立多个文件夹,分类存放sass文件。例如:将variables、mixin、公共样式、私有样式分成多个文件夹存放;

多文件

同一个文件夹的sass可以按模块、功能等等分成多个文件,最终用@import 导入

这样说的有点粗糙,我举个例子吧(下划线开头的sass文件不会编译单独css文件)

——sass
  ——config                //基本变量
  ——mixin                 //函数
  ——common                //公用
    ——header
    ——aside
      ——_list.scss
      ——_nav.scss
      ——_base.scss
  ——compoment             //组件样式
    ——dropdown
    ——lightbox
  ——page
    ——index               //首页
      ——_ad.scss           //广告样式
      ——_content.scss      //内容信息
      ——_info.scss         //个人信息样式
      ——_base.scss         //index样式,@import &#39;ad&#39;;@import &#39;content&#39;;@import &#39;info&#39;;
    ——write               
    ——preview        
      ——_aside.scss       //preview页面独有侧边栏
    ——about
  ——main.scss             //导入所需要的样式,最终生成一个main.css

如上面所示的目录结构,能让人一目了然sass的目录的结构,维护的时候可以快速准确的找到文件。
如果是多页面的项目,也可以最大限度复用代码,而且可以导出公用样式,利用缓存提高加载速度,不用每个页面都重复写一样的代码。

注意:common文件夹的公共样式必须是其他页面所共有的样式,如果有些页面有特殊的样式,应该将会覆盖的css抽取出来,在页面中分别导入不同的私有样式。

根据命名规则限定使用样式

比如说preview页面有一个私有aside样式,可以在这样写preview里面的_aside.scss:

@charset "utf-8"/** 预览页面侧边栏* author:xxx* time:xxxx-xx-xx*/@import &#39;../../common/aside/base&#39;.preview{
  .aside{
    /* css */
    &__item{
      /* css */
    }
  }}

这里需要注意的是,css覆盖会导致重新渲染,影响性能。

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
Next Level CSS Styling for CursorsNext Level CSS Styling for CursorsApr 23, 2025 am 11:04 AM

Custom cursors with CSS are great, but we can take things to the next level with JavaScript. Using JavaScript, we can transition between cursor states, place dynamic text within the cursor, apply complex animations, and apply filters.

Worlds Collide: Keyframe Collision Detection Using Style QueriesWorlds Collide: Keyframe Collision Detection Using Style QueriesApr 23, 2025 am 10:42 AM

Interactive CSS animations with elements ricocheting off each other seem more plausible in 2025. While it’s unnecessary to implement Pong in CSS, the increasing flexibility and power of CSS reinforce Lee's suspicion that one day it will be a

Using CSS backdrop-filter for UI EffectsUsing CSS backdrop-filter for UI EffectsApr 23, 2025 am 10:20 AM

Tips and tricks on utilizing the CSS backdrop-filter property to style user interfaces. You’ll learn how to layer backdrop filters among multiple elements, and integrate them with other CSS graphical effects to create elaborate designs.

SMIL on?SMIL on?Apr 23, 2025 am 09:57 AM

Well, it turns out that SVG's built-in animation features were never deprecated as planned. Sure, CSS and JavaScript are more than capable of carrying the load, but it's good to know that SMIL is not dead in the water as previously

'Pretty' is in the eye of the beholder'Pretty' is in the eye of the beholderApr 23, 2025 am 09:40 AM

Yay, let's jump for text-wrap: pretty landing in Safari Technology Preview! But beware that it's different from how it works in Chromium browsers.

CSS-Tricks Chronicles XLIIICSS-Tricks Chronicles XLIIIApr 23, 2025 am 09:35 AM

This CSS-Tricks update highlights significant progress in the Almanac, recent podcast appearances, a new CSS counters guide, and the addition of several new authors contributing valuable content.

Tailwind's @apply Feature is Better Than it SoundsTailwind's @apply Feature is Better Than it SoundsApr 23, 2025 am 09:23 AM

Most of the time, people showcase Tailwind's @apply feature with one of Tailwind's single-property utilities (which changes a single CSS declaration). When showcased this way, @apply doesn't sound promising at all. So obvio

Feeling Like I Have No Release: A Journey Towards Sane DeploymentsFeeling Like I Have No Release: A Journey Towards Sane DeploymentsApr 23, 2025 am 09:19 AM

Deploying like an idiot comes down to a mismatch between the tools you use to deploy and the reward in complexity reduced versus complexity added.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function