In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
In this issue, the editor will bring you an example analysis of the development of the CSS framework. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.
Philip Walton, a front-end engineer at AppFolio, presented the CSS architecture and some best practices at the Santa Barbara on Rails party, and has been using it in his work.
Web developers who are good at CSS can not only visually copy physical prototypes, but also render them perfectly in code. You don't need to use tables and use as few pictures as possible. If you are a veritable master, you can quickly apply the latest and greatest technologies to your projects, such as media queries, transitions, filters, transformations, etc. Although this is what a true CSS master has, CSS is rarely discussed alone or used to evaluate someone's skills.
Interestingly, we seldom evaluate other languages in this way. Rails developers don't think of him as a good developer because his code is standardized. This is just a benchmark. Of course, his code must be standardized. In addition, there are other aspects to consider, such as whether the code is readable? Whether it is easy to modify or expand.
These are natural questions, and CSS is no different from them. Today's Web applications are bigger than ever. A poorly thought-out CSS architecture tends to weaken development, and it's time to evaluate the CSS architecture like other languages, which should not be left to "hindsight" or to designers alone.
1. Good CSS architecture goal
In the CSS community, it has become a general consensus that it is difficult to come up with a best practice. Judging purely from Hacker News's comments and developers' reaction to CSS Lint's release, most people are against the basic CSS stuff. So instead of laying down a basic set of arguments for your best practices, you should set real goals.
The goal of a good CSS architecture is different from developing a good application. It must be predictable, reusable, maintainable, and scalable.
Predictable
Predictability means that you can regulate your behavior as expected. When you add or modify a rule, it does not affect the unspecified parts. For a small website, a few minor changes are nothing. For large websites with thousands of pages, predictability is a must.
Reusable
CSS rules should be abstract and decoupled so that you can quickly build new components on top of existing ones without having to modify the coding schema.
Maintainable
When you put a new component on a site and perform add, modify, or redesign operations, there is no need to ReFactor the existing CSS, and the newly added X does not break the Y component of the original page.
Scalable
When the website develops to a certain scale, it needs to be maintained and expanded. Scalable CSS means that the CSS architecture of a website can be easily managed by individuals or teams without too much learning cost.
two。 Common mistakes and practices
Before achieving a good CSS architecture goal, let's take a look at some common mistakes that are good for us to achieve.
Although the following examples can be well implemented, but will bring you a lot of trouble, although our intentions and wishes are good, but these development patterns will give you a headache.
On almost every site, there is a specific virtual element that looks exactly the same as any other page, except for one page. When faced with such a situation, almost every novice CSS developer (even the experienced one) will modify it in the same way. You should find something different about the page (or create it yourself), and then write a new rule to do it.
Modify a component based on the parent component
CSS Code copies content to the clipboard
.widget {
Background: yellow
Border: 1px solid black
Color: black
Width: 50%
}
# sidebar .widget {
Width: 200px
}
Body.homepage .widget {
Background: white
}
At first glance, this is definitely harmless code, but let's see if it achieves the goal we set.
First of all, widget is unpredictable in examle. When these widgets appear on both sides of the page or on the main page, developers expect them to be displayed in a specific way without losing their features. In addition, it is not reusable or extensible.
In addition, it is also difficult to maintain. Once the widget needs to be redesigned, you have to modify several other CSS styles. Imagine that if this code is written in another language, it is basically a class definition, and then use that definition and extend it in another part of the code. This directly violates the open / closed (open/close) principle of software development.
Software entities (classes, modules, functions, etc.) should be extended and closed for modification.
An overly complex selector
Occasionally, there are articles that introduce that CSS selectors play an important role in the presentation of the entire site, and claim that there is no need to use any class selectors or ID selectors.
But the deeper the development, the more I move away from this complex selector. The more complex a selector is, the more coupled it is to HTML. Relying on HTML tags and combiners can keep HTML code clean, but make CSS more gross and messy.
CSS Code copies content to the clipboard
# main-nav ul li ul li div {}
# content article h1:first-child {}
# sidebar > div > h4 + p {}
Have a simple understanding of the above code. The first may be to style the drop-down menu; the second is to state that the main title of the article should be different from the H1 element of other pages; and the last is to add some extra space in the sidebar area of the first paragraph.
If this HTML is forever unchanged, then there is nothing to say, but this is not realistic at all. An overly complex selector can be impressive and allows HTML to get rid of apparent complexity, but it is of no use in achieving good CSS architectural goals.
None of the examples mentioned above have the four features of predictability, reusability, extensibility, and maintainability. For example, in the first selector (drop-down menu) example, if a very similar drop-down list needs to be used on different pages and # main-nav is not an internal element, do you need to redesign it? Suppose the developer wants to change some of the tags in div in the third example, then the whole rule will be broken.
An overly generic class name
When creating reusable design components, it is common to override the child elements of attachments in the component's class selector. For example:
CSS Code copies content to the clipboard
...
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
In condimentum justo et est dapibus sit amet euismod ligula ornare.
Vivamus elementum accumsan dignissim.
Click Me!
.widget {}
.widget .title {}
.widget .contents {}
.widget .action {}
Sub-element class selectors such as .title, .contents, and .action can be safely named for styles without fear that these styles will spread to other elements with the same class name. This is absolutely true. However, it does not prevent the same style class name from spreading to this component.
On some large projects, a name like .title is likely to be used on another page or itself. If this happens, the entire title section will obviously be different from what was expected.
Overly generic class selector names can lead to many unpredictable CSS styles.
One rule does too many things.
Sometimes you have to make a visual component of 20pixels in the upper-left corner of the site.
CSS Code copies content to the clipboard
.widget {
Position: absolute
Top: 20px
Left: 20px
Background-color: red
Font-size: 1.5em
Text-transform: uppercase
}
Next, you need to use this component in other areas of the site, so the above code is obviously wrong and non-reusable.
The crux of the problem is that you let the .widget selector do too much, not only specifying the location of the component, but also styling its look and feel. Look and feel can be universal, but location is not. Sometimes, it will be greatly discounted to use them together.
While these may seem harmless, copy and paste have become a habit for some inexperienced CSS programmers. If a new team needs a specific component, such as .infobox, they will try to use this class selector. But if the information box is not displayed correctly where it is needed, as expected. What do you think they will do at this time? In my experience, they break the rule of reusability; instead, they simply copy and paste the code wherever it is needed. Do unnecessary repetitive work.
3. Reason
The general error practices listed above all have a similarity: the CSS style takes on too much.
You'll be surprised to say that, after all, it's a stylesheet, shouldn't it assume most, if not all, styles? Isn't that what we want?
That's true. But generally speaking, things are not that simple. The separation of content from presentation (presentation) is a good thing, but the separation of CSS from HTML does not mean that content also needs to be separated from presentation. In other words, if CSS requests an in-depth analysis of the HTML schema, splitting all the display code from the HTML does not necessarily achieve all goals.
In addition, HTML rarely contains only content, but also represents the overall framework. Typically, the schema contains container elements, allowing CSS to isolate some fixed elements. Even if there is no representation class (presentational classes), you can mix HTML to show the content clearly.
I believe that, given the current state of HTML and CSS, it is necessary to combine HTML and CSS wisely as a presentation layer. The content layer can also be separated by templates and local templates (partials).
4. Solution.
If HTML and CSS are combined as the presentation layer of a Web application, then they need to take some ways to better promote the formation of a good CSS architecture.
The best way is to include as few HTML schemas as possible in CSS. CSS should define the visual effect of an element, no matter where the visual element is. If there are specific components that need to show different effects in different situations, they should be given different names. For example, CSS defines a button component through the .button class selector. If HTML wants a particular element to look like a button, you can use .button. If there are special requirements here, and the buttons here are different from the others (maybe larger and wider), then CSS needs to define a new class, and HTML can use the new class to give the element a new visual effect.
CSS gives the external characteristics of the element, and HTML is called on the page. It is best that less CSS can be called by more HTML schemas.
Accurately declaring elements in HTML not only clearly expresses the design intent, but other developers can also clearly view the markup and know what the element will look like. Without this practice, it is difficult to tell whether an element's appearance setting is intentional or unintentional, which can easily lead to team confusion.
Filling in a large number of classes (classes) in tags is a common flaw, which often requires extra effort. A CSS style can be referenced thousands of times to a particular component. So is it really worth writing such a class over and over again in order to make a display declaration in the tag?
While this concern is valid, it can be misleading. The implication is that whether you use a parent selector in CSS or write thousands of Class yourself, there are some additional options. Viewing the same level of abstraction in Rails or other frameworks can largely maintain a good visual look in HTML without having to write the same class over and over again in the class.
5. Best practices.
I have made a good summary of the above mistakes and put forward some suggestions based on my own experience, hoping that they will help you better achieve your good CSS architecture goals.
Focus
The best way to ensure that the selector does not style some elements irrelevant is not to give them a chance. Selectors like # main-nav ul li ul li div, for example, can be easily applied to unwanted elements. On the other hand, selectors like .subnav don't give them any chance. Applying the class selector directly to the element you want is the best way to maintain the predictability of the element.
CSS Code copies content to the clipboard
/ * Grenade * /
# main-nav ul li ul {}
/ * Sniper Rifle * /
.subnav {}
Modularization
A well-organized component layer can help solve the loose coupling between HTML architecture and CSS. In addition, the CSS component itself should be modular. Components should know how to style and work better, but don't make too many assumptions about layout, positioning, and their relationship to surrounding elements.
In general, CSS should define the appearance of the component, not the layout or location. You should also follow principles when using attributes such as background, color, and font.
The layout and location should consist of a separate layout class or separate container elements (remember that to effectively separate content from presentation is to separate content from container).
Namespace a class
We have examined why the parent selector is not 100% effective in sealing and preventing cross-pattern contamination. A better solution is to apply namespaces to classes. If an element is a member of a visual component, each child element of that element should use a namespace-based component.
CSS Code copies content to the clipboard
/ * High risk of style cross-contamination * /
.widget {}
.widget .title {}
/ * Low risk of style cross-contamination * /
.widget {}
. widget-title {}
Namespacing classes keeps components independent and modular. It can minimize existing class conflicts and reduce some special requirements for child elements.
Create modifier classes to extend components
When an existing component needs to be different in a particular context, you can create a modifier class (modifier class) to extend it.
CSS Code copies content to the clipboard
/ * Bad * /
.widget {}
# sidebar .widget {}
/ * Good * /
.widget {}
. widget-sidebar {}
As we have seen, modifying the component based on the shortcomings of the parent element needs to be reiterated: a modifier class can be used anywhere. Location-based overrides can only be used in a specific location, and modifier classes can be used multiple times as needed. Obviously, the modifier class meets the needs of HTML developers.
Organize CSS into a logical structure
Jonathan Snook mentioned in his excellent "SMACSS" book that CSS can be divided into four different categories: base, layout, modules, and state. The foundation includes reset principles and element defaults; layout is to locate site-wide elements and act as a general layout assistant like a grid system; modules are reusable visual elements; and state is style, which can be turned on or off through JavaScript.
A component is a separate visual element. Templates, on the other hand, are building blocks. Templates rarely stand alone to describe vision and perception. Instead, they are single, reusable patterns that can be put together to form components.
To provide a more detailed example, a component may be a modal dialog box. The mode may contain a gradual website signature in the header, or there may be a shadow around it, a close button in the upper right corner, and the position may be fixed between the vertical and horizontal lines. These four patterns may be used repeatedly by the site, so you rarely think of re-coding and design each time you use them. All of these templates form a module component.
Use classes for style and style
People who have built large websites may have the experience that a HTML element that owns a class may have no idea what it is used for. You want to delete it, but you are hesitant because you may not be aware of its role. Once this happens over and over again, there will be more and more such classes in the project over time, just because team members are afraid to delete them.
In Web front-end development, classes take on too much responsibility, which is why this problem occurs. Styling HTML elements, acting as JavaScript hook, functional testing, automated testing, etc. When so many applications are using classes, it will be very difficult for you to remove them from HTML.
However, this problem can be completely avoided by using some mature conventions (conventions). When you see a class in HTML, you should immediately understand its purpose. I suggest using a prefix, such as .js for JavaScript, to indicate that Modernizr classes can be preceded by .supports, and that unprefixed ones are used to indicate styles.
It will be very easy to find unused classes and remove them from HTML. You can even automate this process in JavaScript by cross-referencing the document.styleSheets object in HTML. If the class is not found in document.styleSheets, it can be safely removed.
In general, the best practice is to separate the content from the presentation, and it is equally important to separate the functions. Using style classes like JavaScript hook can deepen the coupling between CSS and JavaScript to some extent, but it is difficult or impossible to change the appearance without breaking the functionality.
Logical named classes
Most people who write CSS prefer to use hyphens to separate nouns, but hyphens are not enough to distinguish between different types of classes.
Nicolas Gallagher recently wrote a solution to the problem encountered with great success (with minor changes). To illustrate the naming convention, consider the following format:
CSS Code copies content to the clipboard
/ * A component * /
. button-group {}
/ * A component modifier (modifying .button) * /
. button-primary {}
/ * A component sub-object (lives within .button) * /
. button-icon {}
/ * Is this a component class or a layout class? * /
.header {}
From the above classes, we can find that it is difficult to distinguish the type rules correctly. Not only is this confusing, but it also becomes difficult to test CSS and HTML automatically. A structured naming convention should be able to know at first glance the relationship between its class name and other classes, and where it appears in HTML-- making naming easier and easier to test.
CSS Code copies content to the clipboard
/ * Templates Rules (using Sass placeholders) * /
% template-name
% template-name--modifier-name
% template-name__sub-object
% template-name__sub-object--modifier-name
/ * Component Rules * /
. component-name
.component-name--modifier-name
. component-name__sub-object
. component-name__sub-object--modifier-name
/ * Layout Rules * /
.l-layout-method
.grid
/ * State Rules * /
.is-state-type
/ * Non-styled JavaScript Hooks * /
.js-action-name
Redo the first example:
CSS Code copies content to the clipboard
/ * A component * /
. button-group {}
/ * A component modifier (modifying .button) * /
.button-- primary {}
/ * A component sub-object (lives within .button) * /
.button _ _ icon {}
/ * A layout class * /
. l-header {}
6. Tools
Maintaining an efficient and well-organized CSS architecture is very difficult, especially in large teams. Here are some good tools to help you manage the CSS architecture of your website.
CSS Preprocessor
CSS preprocessor is written in PHP5, which has the common functions of preprocessor and can help you write CSS quickly. In addition, some so-called "functional" preprocessors don't actually work well for CSS architectures. Here is a list that you must avoid when using:
● must not nest rules purely for the purpose of organizing code. Only if you output the CSS you really want.
Do not use mixin when ● does not need to pass parameters. Mixin without parameters is more suitable to be used as a template and easy to expand.
● do not use @ extend on selectors, it is not a single class. It makes no sense from a design point of view, it inflates compiled CSS.
When applying component modifier rules in ●, do not use @ extend UI components, which will lose the underlying chain.
@ extend and% placeholder are two very good features in the preprocessor. They can help you easily manage CSS abstractions and do not need to add bloat and a large number of base classes to CSS and HTML, otherwise it will be difficult to manage.
When you use @ extend for the first time, it is often used with modifier classes, such as:
CSS Code copies content to the clipboard
.button {
/ * button styles * /
}
/ * Bad * /
.button-- primary {
@ extend .button
/ * modification styles * /
}
Doing so will cause you to lose the chain of inheritance in HTML. It is difficult to select all button instances using JavaScript.
As a general rule, it is rare to extend UI components or do something once you know the type. This is a way to distinguish between templates and components, templates do not need to be involved in the logic of the application, and can be securely extended using preprocessors.
Here is an example of a pattern referencing the above:
CSS Code copies content to the clipboard
.modal {
@ extend% dialog
@ extend% drop-shadow
@ extend% statically-centered
/ * other modal styles * /
}
.modal _ _ close {
@ extend% dialog__close
/ * other close button styles * /
}
.modal _ _ header {
@ extend% background-gradient
/ * other modal header styles * /
}
CSS Lint
CSS Lint is a code quality testing tool written by Nicole Sullivan and Nicholas Zakas to help CSS developers write better code. Their website says something about CSS Lint:
CSS Lint is a tool to help you find problems in CSS code, it can do basic syntax checking and use a set of preset rules to check for problems in the code, the rules can be extended.
Using the CSS Lint recommendation:
1. Do not appear ID in the selector.
two。 In multipart rules, do not use non-semantic type selectors, such as DIV, SPAN, and so on.
3. Do not use more than 2 combinator in a selector.
4. Do not start with "js-" for any class name.
5. Warning should be given if layout and positioning are often used in non-"I -" prefix rules
6. A warning should also be given if a class is defined and redefined as a subclass.
Summary
CSS is not just visual design, and don't throw out programming best practices just because you write CSS. Rules such as OOP, DRY, Open / close, and Separation from content should be applied to CSS. No matter how you organize your code, make sure that the method really helps you and makes your development easier and maintainable.
The above is the example analysis of the development of the CSS framework shared by the editor. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.