Learn the rules for improving your CSS technology

Source: Internet
Author: User
Tags bit set mozilla developer network css preprocessor

Share some of the things I've understood in the last few months, which are not snippets or CSS tricks, but more like general rules or best practices, as follows:

    • Do not let your code out of your control, as concise as possible

    • Master the basics and learn CSS skills

    • Keep your code reusable

    • Object-oriented CSS

    • CSS3 know what he can do and what parts you can use.

    • Progressive enhancement and graceful downgrade

    • CSS preprocessing tools

    • Times

    • Each other

    • Practice makes perfect

What do you want to say? You ready? Then let's go on down.

1. Do not let your code out of your control, as concise as possible

Don't let your code get out of your control.

This is a general recommendation for programming, not just for CSS. When you start writing code, think about the following questions:

    • How do I make it happen?

    • Is there any other way to do it?

    • How to optimize (simple, maintainable, etc.)?

The rush to code can be a waste of time, and you may have spent one hours not realizing it, having to start over again, which should not happen.

If you spend hours writing a CSS slide, and ultimately no way to use a JS slideshow plugin or something else, it is very painful, not that you did not succeed, but wasted a lot of time. If the project has deadline, you are going to have a tragedy.

Keep his simplicity.

CSS is simple, but if you want to, it can also become very complex. In many scenarios, the simplest is the best. When you want to achieve something, ask yourself: Is there a simpler way to do it? The answer is often yes.

For example, a simple horizontal navigation bar can be implemented in a number of ways:

    • list element floats;

    • Change the list element display property to inline;

    • Change the list element display property to Inline-block.

The simplest-set display:inline, do not need to clear the float, do not need to clear the inline-block caused by the white space, only need some padding can, end.

2. Master the basics and learn CSS skills

Not only mastering the CSS, mastering everything from the ground up. It is impossible for a man to become a master without a thorough understanding of the most basic things.

CSS Basics

What is a CSS foundation? You may hear different voices, and this is something that cannot be expressed in words. But I think that the basis of CSS is the following two parts:

    • Box model: Each element in the CSS is a box model (block-level or inline), containing a wide height and various padding margin border. This is the most important and detailed can be read here.

    • Weight: Learn which attribute has the highest weight and is important in debugging CSS. Read more about Assigningproperty values, cascading, and inheritance.

CSS Tips

When you understand the above principles, you are on the path. So now you might be dealing with some special situations, and here are some of the following:

Forgot to set the position in the parent element

At this time you will think: Pit Daddy Ah, how things run to the top left corner of the page??? You forgot to set position:absolute or relative for the parent element.

Add a lower layer of skill

Every front-end is plagued by cascading contexts. This example tells us that you cannot apply the Z-index property to a child element that has triggered a cascading context (perhaps z-index,transform or transparency). There is no workaround, once you have met, will definitely remember.

Forget to remove floating tricks

Your layout is messed up and the container flies. You burst into tears: it was swollen and touched. Please check the float below and may forget to clear the float.

Remember that if a container contains only floating elements, he will collapse unless you clear the float or set the height or overflow property.

Such examples abound, and if you continue to write that will be endless, this is not my purpose of this article.

I just want to point out that every day, people will constantly find that CSS has a lot of features and special circumstances. You may step on a hole this time and you'll know how to deal with it next time.

3. Maintain the reusability of the Code

Dry representatives do not repeat themselves. This is not unique to CSS, which is suitable for any language.

Its core idea is that code that can be reused should not be written nth times. In other languages it means encapsulating a function, which in CSS often represents the need to use a reusable class instead of a property of a repeating application. This will be explained further in the object-oriented CSS that follows. In fact, this is very simple for refactoring, let me explain:

When you find a piece of code used multiple times in your stylesheet, you need to refactor it and eventually become only one (reusable). Example:

You understand? You're going to wonder, what's the difference between these two? There are two points to consider: performance and maintainability.

About performance: Fewer rows means that the browser parses the CSS faster. According to the following, the browser will apply color to two selectors at the same time, without parsing two times.

With regard to maintainability, if you need to modify a similar color so that you only need to modify one line, here is probably just two lines, if 50 rows, 100 rows.

Extended Reading

    • DRY CSS, don ' t repeat Yourcss

    • DRY Css:adon ' t-repeat-yourselfmethodology for creating efficient, unified and scalable style sheets

4. Object-oriented CSS

What is this stuff?

Oocss means object-oriented CSS, which often appears in other object-oriented languages. This means using an "object", typically an instance of a class (containing some properties and methods). You may ask: what does this have to do with CSS?

First of all I want to show that oocss more like a concept, CSS is not really "object-oriented programming", because there is no namespace, functions, methods, classes, conditional statements and so on. So if you talk about Oocss, you may be ridiculed.

In fact, I think so, but we can use this idea to promote the writing of CSS, so that the performance of the site, improve maintainability.

What should we do?

Very simple, use the class name, various class names. You can think of your site as a place with lots of "methods" and "components," and try to find the duplicates and reuse them as "objects" (class names).

To make your objects more accurate, there are two points to note:

    • Separation structure and performance

    • Separating containers from content

Individual structures and styles

Separating the structure from the performance is important so that you can manipulate the part that is responsible for the display, making it appear multiple times in the site and acting on different elements. Take a look at the following code, which can act on a box, a picture, or a button:

In addition, we can replace it with a class name called. Skin and apply it to the element you want to use.

This will make the CSS style sheet easier to understand, easier to maintain, and faster to parse.

Separate container (structure) and content

I think this is the most important point of OOCSS: Each component has its own code, rather than defining it in conjunction with a specific part of the page when you write the page one at a time. In your site, similar components should be reused, just like the following code:

This time, whether I use H2 from the bottom of the page again, or if I use the same idea with H3, you can create a class and set a style for the class instead of styling the element individually.

About the one that never uses an ID?

When Nicole Sullivan proposed the concept of OOCSS, the most enthusiastic discussion was "never use an ID selector?" "Nicholas C. Zakas and Nicole Sullivan specifically opposed the use of ID selectors in their csslint (CSS quality checker).

To understand Nicole's point of view, we must recognize that the ID selector will have some problems in use because of its high weight. The following code (code from here):

If the first Twitter link turns black, you have two options: give an ID, or take advantage of it! Important selector to machine gun hit mosquitoes. If the header is a class name, there is no such problem.

This is why Nicole Sullivan said "no ID".

I quote Harry Roberts a discussion of this topic as the end of this verse.

[...] I havedecided A blanket ban is sensible. Save yourself many potential headachesand never use IDs in your CSS files.

Of course the ID is available in principle, and it's easy to take effect

My understanding of Oocss

In fact, I'm not familiar with OOCSS. Because I'm not working on a large web site with a lot of front ends. Oocss is useful for large web site architectures, but not for single-page combat.

But while I didn't apply oocss, I focused on component reuse in front-end work, maintainability of stylesheets, and performance. This is also OOCSS's attention, so in some ways, my work is not much different from oocss.

Extended Reading

    • Anintroduction to Oocss

    • Object oriented CSS

    • oocss.org

    • Don ' t use the IDs in CSS selectors?

    • oocss--Concept article

    • oocss--Core Chapter

5. CSS3: Know what he can and what you can use

Now let's stop the conceptual discussion and do some dry stuff: CSS3, although there is no definite definition of this thing yet.

Unlike CSS 2,which is a large single specification defining various features, CSS 3 isdivided into several separate docume NTS called "Modules". Each module adds the new capabilities or extends features defined Incss 2, over preserving backward compatibility. [...] Due to the Modularization,different modules has different stability and statuses.

---from Cascadingstyle Sheets on Wikipedia

Now let's talk about some of the features that have been implemented by modern browsers.

At present, from rounded corners to gradients, from transparent to shadow, pseudo-class, everywhere CSS3.

What can you do to learn?

I think that by using CSS3, you can reduce the number of HTTP requests (picture requests), reduce the amount of tags, and reduce JS code. Let's start to say:

    • Rounded corners, one line of code instead of four small pictures to spell four fillets;

    • Transparency and alpha channel support: a single line of code instead of a translucent PNG;

    • More advanced selector: Do not need JS to write;

    • Flexbox: A few lines of code replace an entire layout frame;

    • Gradient: A few lines of code instead of a background tile picture;

    • Multi-background: No need for multiple containers;

    • Pseudo-Class: Decorative elements do not need additional tags to define.

I can go on, but I'm sure you know what I mean: know what you can do with CSS3. Do you need to make a directory? You can use pure CSS to implement, with CSS counters, you need to make a beautiful custom border? You can use the Border-image property to implement.

CSS can do countless things, CSS3 is the same. You need to understand what CSS can and cannot do with the force.

But deep into these, there is no shortcut, only through the constant reading of documents, self-exploration. For example, you can use the Calc () property to calculate, but if you want to make a six-column high-level layout, you will definitely have a cup.

What can you use to learn?

The biggest problem with CSS is browser compatibility. The situation in CSS3 has become even worse. When you keep experimenting with CSS3 properties, it's a nightmare you can't linger on.

For example, the most familiar CSS3 property: Border-radius, the cup is IE8 below, and Opera Mini browser still do not know this thing. In fact, Chrome and FF do not have a consistent rendering of fillets.

What does this mean for a front end? Graceful downgrade. If you do fillet, you still need to use multiple images to make fillets, in addition to Border-radius, and try to keep the big browsers consistent.

This is my usual thinking step when I want to use CSS:

    • What am I going to do with this CSS?

    • I understand what I'm going to do, is this in the CSS2 spec?

    • Must be, to the end.

    • No, skip to step three.

    • How's the compatibility of this thing?

    • Very good compatibility ah, end

    • Compatibility is general, skip to step Fourth

    • Is this the icing on the cake or the demand?

    • This is the icing on the cake, then I can only gracefully downgrade the low-end browser.

    • This is the demand Ah! Skip to step Fifth

    • How do I deal with this requirement in an incompatible browser?

Now take the gradient as an example:

    • Do you want to use gradients here?

    • Use it. Is there a gradient in the CSS2?

    • The gradient is CSS3, okay.

    • What about compatibility?

    • OK, generalize, ie8 the following Operamini does not support CSS3 gradients (this is obviously wrong

    • Is this the icing on the cake or the demand?

    • It's just a more flashy tool, not a point. Do not support I will use a monochrome instead of it.

    • Demand requirements Here is the gradient Ah! I have to find a compatible.

    • How do I get it to work on a browser that doesn't support

    • Use the background image.

If you think about these steps with CSS, there's a mindset to deal with browser compatibility and graceful downgrades.

Attention! Be sure to pay attention to the users of your products! If you want to do mobile apps or mobile devices, you can use the CSS3 attribute vigorously, don't worry. But if you make a banking system. Sorry, most of the users are below IE8

Providingfallbacks

Depending on the situation, compatibility with low-end browsers can be painful and can be annoying.

No fallback orsimple Fallback

If some of the features that enhance the user experience are not supported, you won't have to force compatibility, which is cool.

There are some situations where compatibility is easier.

In short you need to write two copies of the properties to achieve this effect, for the old version of the browser with the modern browser version.

In the above example, if the browser does not recognize Rgba and HSL colors, he will read the first line and the third line as a downgrade. Then modern browsers will overwrite these properties and render them with new properties.

Modernizr

Now when we talk about CSS3, we will definitely mention a library Modernizr. He can do HTML5 and CSS3 feature detection on the browser. It may sound like a big one, but the library has a very good performance.

Anyway, sometimes you have to know exactly if the browser supports a particular feature. Because, to us, to provide another graceful downgrade version, you need to know his CSS properties.

If you are going to provide a downgrade scenario, you will need to rely on the two classes (. no-opacity and. no-pointerevents) provided by MODERNIZR, but cannot trigger two at a time. When using the new technology, be sure to remember the graceful downgrade, which is important to the user experience, if not, be sure to inform the user.

Extended Reading

    • CSS Current work withtable of specifications

    • webplatform.org

    • MODERNIZR for feature detection

    • Caniuse for the browser support

6. Progressive enhancement and graceful demotion

These two concepts are certainly familiar to everyone, especially the graceful downgrade. In fact, there is a little difference between the two.

Progressive enhancement

incremental enhancement, you need to develop a basic need and functionality, and then enhance the user experience based on browser support. When you use it, you need to use some HTML5 properties to remind you of some missing parts (for example, you can get the best experience under a certain browser). This is a way to enhance the user experience based on the browser engine.

Graceful downgrade

When you talk about graceful demotion, it's usually a low-end browser offering an alternative to unsupported features. His form is usually discussed from the high to the low. For example, you need to specify in the canvas tag so that users will know when the browser doesn't support canvas.

How are they different?

In fact, it's no different. Some features are present on a modern browser, which is an alternative to low-end browsers. This is a process: you can make the Web page in the modern browser effect is very cool, also have to scruple ie, or ignore, it is entirely up to you. In fact I want to say: The user experience of different browsers is absolutely different, even if you need to provide some basic features, please remember to use the new features to enhance your browser or application, which is very good.

Extended Reading

    • Progressiveenhancement and graceful degradation

    • understandingprogressive Enhancement

7. CSS Preprocessing tool

CSS preprocessor is probably the hottest topic of the year. Is this thing really good? For what? Do I need to use it? With what kind of? This is a hot topic in CSS circles.

I will deal with this problem in an objective manner at this stage. The first thing to make clear is that if you don't want to use a preprocessor, don't use it, and then you won't get tangled up. Not having a preprocessor doesn't mean you're not a good front end, just that you might not be able to do something. But for the preprocessor, you still need to have your own independent thinking.

Next, what is a preprocessor? The preprocessor, in fact, compiles some of the sentence segments into the language required by other engines, such as browsers. All languages are precompiled, such as HTML can use Markdown or jade. Less,sass and stylus are both pre-processors of CSS. Coffeescript is the preprocessor for JS, and of course the preprocessor for PHP: cakephp.

What's the point?

The preprocessor gives CSS some features that are based on object-oriented language, such as

    • Variable (variables)

    • function of the functions (with parameters)

    • Namespaces (namespaces)

    • Nesting (nesting)

    • Conditional statement (conditional statements)

    • Operation (Operations)

    • Others (and many more)

Sounds appealing, doesn't it? Maybe you want an example to figure out what's going on. Let's look at the following CSS navigation bar.

Look at a version of SCSS processing

The basic function of the preprocessor is to translate these expressions into CSS, the results are certainly the same, and the processing logic is different. The preprocessor automatically processes and outputs the results without requiring the support of the Calc function.

In the end, you get a more readable style sheet (with nested and variable) and more maintainable (including variables and functions). The above is just an example of what you would see in a real project.

How to choose?

Now there are a number of different CSS pre-processor, they have their differences, but also in the nuances of the difference. The choice is entirely in your hands. Here are a few main options:

    • Sass (written in Ruby)

    • Less (written in JavaScript)

    • Stylus (written injavascript)

    • Crush (written inphp)

The best way to do this is to find out whether they are the perfect fit for your project and your needs. This is determined by a number of factors, if the whole list is beyond the scope of this article, but you can find some relevant CSS preprocessor data.

My understanding of CSS preprocessing?

I can't say I'm proficient in CSS preprocessor, but I like it very much. He has perfected some of the most useful features that are missing from CSS: variables, nesting, and conditional statements.

I've had a little fun before, and I've benefited a bit. Using less I perfected the previously crafted CSS loadinganimations,less application in loops, automatic prefixes, and keyframes.

I also tried sass and compass. What shocked me was that it was easy to install and ran smoothly on Ruby. So I think sass + compass bunker. You can read my article: Why I abandoned less to choose Sass.

But I still need to fully write the normal CSS, which also occupy the majority of my work. But in the end I think everyone will use CSS preprocessor. CSS lacks some very useful features, and the preprocessor just fills this void.

Extended Reading

    • Sass vs. Lessvs. Stylus

    • Musing on preprocessing

    • Deep Diveinto CSS preprocessors

    • Guidelinesusing Oocss and CSS preprocessors

8. Keeping pace with The Times

The language is constantly evolving, and CSS is a notable example. The CSS draft is endless, and browser vendors are constantly implementing these.

So you need to keep up to date with the new technology, although 1:30 won't work, but can you see if the Chrome development version is supported? Will Chrome and Safari,ff,opera future versions support it? You need to constantly develop your horizons in CSS solutions and CSS issues.

Extended Reading

    • Cascading Style Sheets Home page

    • Caniuse.com for browser share and compatibility

    • Mozilla Developer Network forexcellent Documentation

    • HTML5 Rocks for latest, cutting-edgetutorials and articles

9. Complement each other

Reading the source code is one of the best ways to learn programming. CSS is the client, you can use WebKit Inspector, Dragonfly, Firebug F12 and other tools to see CSS. At the same time, the Internet is very open, everyone is happy to open source.

Another way to do this is to follow the tutorials and go through them, and then write them back from scratch. Look for the answer after the problem and then continue.

If you feel that you are already familiar with CSS and want to drill into CSS, you need to write some demos to test those experimental CSS properties, or to solve a different idea of a problem. Learning.

The former, Chris Coyier, Timsabat and Alex Vazquez three-bit set up the Codepen, he is an online sharing front-end code platform, you can freely add the library you need, such as jquery, jquery UI, MooTools, YUI, Prototype, Zepto, Dojo, Ext js,prefixfree and so on. You can also use some preprocessor such as Haml, Markdown, Slim, less, SCSS, Sass, Coffeescript.

Learn other people examples of websites:

    • Codepen

    • CSS Deck

    • Dabblet

    • Thecodeplayer

    • CSS3 case

10. Practice makes perfect

Practice is the real truth. So the best advice: keep practicing. Practice makes perfect It's not that you keep building your station from scratch. You can find some diagrams from dribbble and implement them with pure CSS. In the end you may not necessarily use it, but as you learn, that's enough.

I've said it before, master the basics and know the skills. CSS has a lot of pits, pits is part of Csser's daily work. And the pits are written code when stepping out, only stepping over, resolved, can improve.

At the same time I suggest you to share your own code, so that everyone to make suggestions, take the top of the rectangle. You can throw it into the jsfiddle and share it in the group and ask if you can throw up the groove.

Learn the rules for improving your CSS technology

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.