Last weekend, BECAUSE I had to write PPT, I didn’t hurry to sort it out, so I missed another one. In this issue, most of the content will revolve around ideas mentioned in @Bill Mei’s article Top 10 Most Deadly CSS Mistakes Made by New and Experienced Developers. Although some of the points mentioned above are not completely correct, they still have corresponding reference value. It is up to you to decide whether to choose or not. If you have any experience in this area, please share it in the comments below. In addition, I will simply sort out some interesting new things in the back. For those of you who are interested, please read on.
10 Most Deadly CSS Errors
Over the years, many engineers, both experienced drivers and novices, have made common mistakes when using CSS. CSS has always been a simple but not easy language (unintuitive and difficult to use) that hasn’t really been explored much, and there are many common mistakes that can get in the way of a project. If we could avoid these errors when we were writing CSS, we would be much better off in actual development.
Here are 10 common and deadly mistakes in CSS writing.
The next 10 are from @Bill Mei’s Top 10 Most Deadly CSS Mistakes Made by New and Experienced Developers.
You write selectors that follow the DOM structure too much
Some developers like to pursue a minimalist style and try not to have a lot of class names in HTML by using DOM structures as CSS selectors so that their selectors follow the structure of the DOM tree. Let’s say we have a DOM structure like this:
<body>
<div class="container">
<div class="main-content">
<div class="blog-row">
<div class="blog-col">
<section>
<article>
<a href="#">This link is not bold</a>
<p><a href="#" class="bold">This link is bold</a></p>
</article>
</section>
<section>
<a href="#">This link is not bold</a>
</section>
</div>
</div>
</div>
</div>
</body>
Copy the code
Some students will add style to a link like this:
body .container .main-content .blog-row .blog-col section article p a {
font-weight: bold;
}
Copy the code
Even when using CSS processors, there are infinite levels of nesting, such as:
body {
.container{
.main-content{
.blog-row{
.blog-col{
section{
article{
p{
a{
font-weight: bold;
}
}
}
}
}
}
}
}
}
Copy the code
Especially in CSS processors, many experienced drivers, not to mention novices, have errors like the one above.
While many drivers advocate DOM structures to be as simple as possible when writing HTML structures, they don’t advocate such unconstrained minimalism. This minimalism, while keeping HTML clean, can clutter UP CSS, making it harder to understand, debug, and change. As the example above shows, CSS can become inflexible because long CSS selectors take on the task of copying THE HTML structure, but this is not what CSS should do.
The job of CSS is to provide style; The job of HTML is to provide structure. This is one of the most fundamental principles of Web building. It would be a mistake to pursue DOM simplicity without considering CSS and its interplay with CSS. In addition, this way of writing CSS, which depends on the strength of the HTML DOM structure tree, can also cause fatal errors. For example, if you make changes to the HTML structure, the CSS selector will also make changes, and this long chain combination is the most prone to error. It also creates a lot of unnecessary work.
Instead, I suggest that CSS classes and HTML DOM should be properly combined. If you need to select a specific element from the page, you should add a class name to that element to do so:
.bold {
font-weight: bold;
}
Copy the code
Even if you want to use this long combination to locate DOM elements, I strongly recommend:
The CSS has no more than three levels of selectors.
Fortunately, there are now many ways to avoid this, such as using StyleLint to monitor your CSS code and keep selectors from nesting beyond three levels. You can also use CSS-in-JS and CSS Modules to maintain your CSS code. Especially today (as of 2019), this approach is more widely adopted.
If you’re interested in CSS-in-JS and CSS Modules, I suggest you spend some time reading the following articles:
- Use of CSS Modules in React
- Differences between scoped CSS and CSS modules in Vue
- Postcss-modules: Make CSS more powerful
- Write CSS postures in React
Having said that, we should avoid over-targeting or specifying too many selectors in our projects, and avoid using them! Important. The comparison of CSS weights makes it easier to see why selector weights are bad. If a selector is overweighted, it will be easier to adopt, and if we want to override it with another selector, we need a selector with a higher weight. This is where a lot of students have trouble overwriting styles.
The battle for CSS selector weights is always in your CSS, which is a pain for many experienced drivers and novices. If you are new to CSS, it is essential to master the calculation of selector weights:
- CSS selectors
- CSS Specificity: Things You Should Know
- The Definitive Guide to CSS Cascading and Specificity
- CSS Specificity
Speaking of CSS selector weights, I’m back on @elijah Manor
If the image above doesn’t help you figure out how to calculate CSS selector weights, here’s a calculator to help you:
Ignore SEO when writing HTML
Search engine optimization (SEO) is not just about coding and handing it over to the marketing team. We need to take SEO into account when coding, especially because of some of the factors that affect SEO. Because the impact of SEO factors once produced, then the follow-up to optimize the difficulty will be greater. Such as a URL Scheme for a website or a service architecture.
It is well known that semantic tags in HTML are one of the factors that affect SEO, because the choice of tags affects how search engines interpret and rank content. If you want to appear near the top of your search results, you need to select the right tags.
Suppose you’re writing an article about a CSS tutorial. You can put everything in a
The advantage of choosing more specific semantic tags rather than generic non-semantic tags is that you can provide search engines with more information about your site so that search engine crawlers can better understand and deliver content relevant to readers’ search queries.
For example, the HTML tag for the title of an article has six potential title tags, h1 to H6, sorted from most important to least important (the smaller the number, the more important).
is your most important title because it is a special signal that search engines will interpret as either the title of your content or the title of your page (, most search engines consider both). Also, if your user is visually impaired and uses a screen reader, most screen readers will know to read < H1 > out loud immediately because it will assume that this is the title of your content.
This also means that if you use < H1 > to handle anything that is not a title, or if you have multiple < H1 > on a page, the search engine will get confused and your “real” title (the one you want the search engine to recognize in the first place) may not show up in the search results. Another case is to have multiple
nested in different parts, such as:
<article> <h1>My cool blog post</h1> <p>This blog is so cool! </p> </article> <footer> <h1>Contact Us</h1> <p>Tel: 867-5309</p> </footer>Copy the code
Although there are two
tags on this page, the first is in
and the other is in the
How to Section Your HTML (@Daniel Tonon’s How to Section Your HTML) goes into this in depth:
To learn more about the relationship between HTML tags and SEO, read the following article:
- 8 Meta Tags That Improve SEO
- 5 Easy HTML Tags Anyone Can Code and Every Webpage Needs
- Meta Tags in 2019: Why are They Important in SEO?
- 7 Essential HTML Tags that Separate SEO Pros from the Rookies
- The 10 Most Important HTML Tags You Need to Know for SEO
- HTML Tags for SEO: to use or not to use?
With the rise of JavaScript frameworks like Vue, React, etc. Many students may not pay much attention to SEO when they use these JavaScritp boxes to develop pages. In fact, there are a lot of discussions about SEO in the development page of Vue and React in foreign countries.
- Is My Single-Page App SEO Friendly?
- Build a Vue.js SEO-Friendly SPA with Prerender & Other Tips
- Vue.js SEO Tips
- Essential Guide to Improve SEO in Single Page Application Vue.js
- SEO vs. React: Web Crawlers are Smarter Than You Think
- The Ultimate Guide to JavaScript SEO
There was also a discussion on Reddit and Zhihu:
- How do you deal with SEO if you want to use Vue or React for the front end?
- React or Vue, how to do SEO optimization?
Finally, I recommend Prerendering as the best SEO solution:
The best SEO solution, and SSR replacement for JavaScript websites. It’s like SSR with no need of coding.
usepx
unit
It is not a mistake to use px units, but it depends on the scenario used. The real mistake is to use absolute units instead of relative units.
For more information about CSS units, read The illustrated CSS: CSS Values and Units article or click here to learn more.
We prefer to use relative measures such as EM, %, REM, and possibly other methods. This ensures that web sites can be scaled according to font size.
P {font-size: 16px; line-height: 20px; margin-bottom: 8px; } // Body {font-size: 16px; } p { font-size: 1rem; The line - height: 1.25; Margin - bottom: 0.5 em. }Copy the code
For example, the following figure epitomizes the benefits of using EM units:
Up to now, the problem of using px as an absolute unit is that it cannot be well adapted to different terminals, especially mobile terminals, which face more complex scenarios. If using px units does not keep your Web page or Web application in the same proportions everywhere, you must try to place your elements in relative terms, not absolute terms. Otherwise, the available space on the screen does not scale properly to each window size. Relative units use this simple PX to lock your design to a specific zoom level, making it difficult to scale your design to different devices.
In a mobile world, I would recommend using Windows units for measuring units, making it easier to scale your design across different devices. If you are interested in this area, I suggest you take some time to read:
- Use Flexible to achieve terminal adaptation of H5 page
- Talk about the adaptation of the mobile page
- How to use VW for mobile adaptation in a Vue project
- Windows unit on mobile tips
- Single screen page responsive adaptation play
Trying to achieve “pixel level” perfect design
More generally, “pixel-level” perfect design is not a good goal when writing CSS.
Modern Web pages or Web applications must run across multiple devices (mobile devices, desktops, tablets, TV screens, and watches) with a variety of screen sizes, screen resolutions, operating systems, user Settings, and JavaScript engines that interfere with the ability to render a perfect “pixel-level” design.
In my opinion, a single-minded pursuit of “pixel-level” design perfection would require additional code to handle, which would introduce greater complexity and potential risk. It can be said that “the contribution is not proportional to the benefit”.
However, it is important not to confuse “pixel level” perfect design with good design. Truly great design is to leave a lasting emotional impact on the user. That’s the joy they get when they open your product, and the joy they get from your Web application. And none of this is because you chose 16pt over 15pt.
Interrupt document flow
The tricky part about CSS is that you can achieve the same visual effect using different CSS code. For example, there are many ways to center elements on a page horizontally and vertically, and using any one of them will give your users the same look.
Amos compiled a list of tips for 23 ways to achieve vertical center.
While there are many ways to achieve the same effect, I recommend that we implement the effect without interrupting the flow of documents. Because interrupting the flow of documents too often (for example, overusing float) increases memory usage and makes it harder for other people to understand, or even yourself.
When there are multiple solutions to achieve the same visual effect, I prefer to use techniques with less memory space.
Do not separate design from layout
CSS’s job is to provide style; HTML’s job is to provide structure. In general, you should first write HTML in a way that captures the hierarchical structure of the page’s information. That is:
When writing HTML, you should ignore any design concerns.
Then, add CSS to make it look good visually.
While HTML provides structure, it can’t always position an element exactly where you want it to appear on the page. Therefore, you can use CSS to build the correct layout of the page so that elements appear in the right places. Once an element is placed in the right place on the page, it can be easily decorated to make it look nice without worrying about its placement. Therefore:
Layout CSS and CSS beautification are doing different things.
Here are two simple examples:
// Bad example.article {display: inline-block; width: 50%; margin-bottom: 1em; font-family: sans-serif; border-radius: 1rem; box-shadow: 12px 12px 2px 1px rgba(0, 0, 0, .2); } .sidebar { width: 25%; margin-left: 5px; <div class="article sidebar"></div> <div class="article sidebar"></div> inline-block; } .article { width: 50%; margin-bottom: 1em; } .sidebar { width: 25%; margin-left: 5px; } /* Lipstick */ .card { font-family: sans-serif; border-radius: 1rem; box-shadow: 12px 12px 2px 1px rgba(0, 0, 0, .2); } <div class="article card"></div> <div class="sidebar card"></div>Copy the code
The Separation of CSS Layout AND CSS beautification efforts, also known as Separation of Concerns, is a universal principle of software engineering that helps keep code maintainable and easy to understand.
We want to use the right tools to do this, because separating the CSS in this way makes it easy to move an element to another part of the page without staining the Lipstick CSS, and we can easily change Lipstick without breaking the Layout. Mixing the two approaches forces us to do both at the same time every time we add a new feature.
Moving ahead
With the increasing popularity of mobile terminals, mobile websites (or applications) become the mainstream. A lot of people start talking about “mobile first,” which means the desktop (PC) is a second-class citizen. Mobile-first advocates, by contrast, show the opposite behavior, writing code first for the desktop and then trying to cram websites into mobile. They use @Media to handle exceptions on mobile devices, but in reality it should be on the desktop.
In this age of mobile, your users will find you on their phone first, and then they’ll like your product enough to play it on the desktop. But in the eyes of your designers, developers, and product managers, is mobile really number one? Do you code for mobile first and then build for desktop? Do your designers create wireframes and models for mobile first, and then wireframes and models for desktop? Do you perform A/B testing on the mobile version and solicit user feedback before testing the desktop version?
Container {width: 980px; padding: 1em; } @media (max-width: 979px) { .container { width: 100%; Padding: 0.5 em. Container {width: 100%; max-width: 980px; Padding: 0.5 em. } @media (min-width: 980px) { .container { padding: 1em; }}Copy the code
Another major reason is that it’s easier to scale from mobile to the big screen; But removing elements from a large screen to make them fit on a smaller screen can be tricky.
No naming scheme is used
Namespaces are one honking great idea — let’s do more of those! — PEP 20: The Zen of Python
Naming elements in CSS is always a pain in the ass, and you’ll be thrilled if you just write code without thinking about naming schemes. For example, when you add a class name to an element, you might name it.img,.image,.blog-img,.img-blog, and so on. If you call it.blog-img, then you’ll also accept.ad-img and.thumbnail-img, right?
Naming an element may seem like a small thing, but CSS is harder to refactor than other languages because we currently don’t have any static analysis tools for CSS to perform automatic refactoring or renaming. CSS classes can be added, removed, and constructed dynamically using JavaScript, so it’s impossible to find “undeclared” CSS selectors — just because a CSS fragment isn’t used in a state on a page doesn’t mean it’s never been used before.
In addition, if your team can’t agree on whether to call it.center,.centre,.centered,.text-center, or.align-center, the BEM won’t solve the problem.
Using CSS-in-JS in some JavaScript frameworks solves this problem in part because they remove the global scope of CSS and encourage you to associate styles with their associated components. However, CSS-IN-JS has not been widely adopted, and there has been much controversy.
Another major reason is that developers are hesitant to remove anything that might damage the site. So it’s better to err on the side of caution than to add junk code. Even worse, unless you work hard to promote and clearly communicate your design system, it may go unnoticed as your colleagues avoid reading your documents and continue their old habits.
Not reading documents
This may seem simple enough. For example, Bootstrap is used. Many students think that it is ok as long as it is installed. Unfortunately, if you don’t really understand the CSS Framework and accidentally violate its principles, it can often cause more problems than you can solve by referring to it. Whether you are using open source Design systems such as Bootstrap, Material Design, Foundation, or your own team’s Design system.
Therefore, before using any framework or system, it is important to take some time to read the relevant documentation.
It’s important to read the documentation carefully, because many frameworks require you to cancel muscle memory extracted from previous frameworks, and you won’t know where the flaws are until you read the entire manual. For example, component inheritance is a common pattern in older front-end frameworks. However, new frameworks like React work best when they use composition rather than inheritance. If you skip reading the document, you probably won’t realize this, and you’ll default to the inheritance pattern you’re used to.
More generally, it’s dangerous to get caught up in muscle memory developed from old technology, which leads us to make one last fatal mistake.
Not systematically learning CSS as planned
Technology is constantly evolving, and the only way to stay relevant is to follow a plan of continuous learning and improvement.
Rote learning from dogma is dangerous. Some experienced developers instinctively recoil when they hear “Inline Style,” having been taught early in their careers to “separate Style and structure; Never use inline styles “**.
In fact, “never use inline styles” is a long-ago best practice. That was the context that made HTML difficult to read, debug, and update. However, the slow progress of the technology ultimately upended the assumptions that led to these “best practices.” New assumptions lead to new best practices.
Inline styles are only a real pain to write inline, but if you use a CSS-in-JS library to manage your inline styles, these alleged disadvantages disappear, leaving you with only modular code, automated testing, and simple administration.
If you stick to the dogma of “never use inline styles,” you won’t have the curiosity to explore what the original assumption means when it changes. It’s important to learn CSS from the ground up using a systematic, structured plan, rather than just searching for tutorials that focus on superficial practice.
Unfortunately, I tried to find free online resources to help you learn CSS in a structured, systematic way, but didn’t find any good ones. Existing CSS resources are either too technical and assume that you already know browser rendering, or they offer simple tips and don’t teach you the basics of CSS.
Because there are no good resources to give you a reliable mental model of CSS, a lot of times problems are solved by searching, copying and pasting. As a result, many people’s knowledge of CSS is patchy enough to solve specific bugs that come up, but when faced with a Bug that seems to take hours to fix and is hard to understand, they immediately feel completely helpless.
And there has always been an unwritten understanding throughout the front-end community.
CSS is very simple, and because of its simplicity, it feels easy. Understand its properties and use it.
Because of this misdirection, people think CSS is easy and doesn’t cost anything to learn. Some students may even think CSS is a Slam Dunk.
Again, I want to make a different point: CSS is simple, but it’s not easy:
Unlike a programming language that requires knowledge of loops, variables, and other concepts, CSS is pretty easy to pick up. Maybe it’s because of this that it has gained the reputation of being simple Simple in the sense of “not complex”, Mistaking “simple” for “easy” will only lead to heartache.
Some of the views listed above may not be all right, but they are quite valuable. It’s not a skill, but it helps me learn more skills.
usebackdrop-filter
Achieve frosted glass effect
Frosted glass effect by Facundo Corradini (
@facundocorradini) on
CodePen.
The frosted glass effect dates back to the effects on iPhone devices.
Background-filter has been known since the introduction of the use of filters in CSS3 Filter 10 Effects and Advanced CSS Filters in 2015. Back then you could only see it in Safari, but starting with Chrome 76 you can also see the frosted glass effect of background-Filter.
The HTMLoutput
The element
Most people have probably heard of the input element, but not much about the output element.
In fact, the OUTPUT element was added in W3C HTML5 Working Draft 12 (February 2019). Prior to this working draft, it was referenced in HTML5 and is directly defined in Web Forms 2.0.
Some of the details of output have changed since the original definition in the HTML specification, but the element remains in the family of form elements. The definition of output is now changed from “the output element represents the result of a calculation” to “the output element represents the result of a calculation performed by an application or a user action.”
Let’s look at a simple use case:
<form oninput="added.value=parseInt(i1.value)+parseInt(i2.value)">
<input type="number" min="0" name="i1" value="0"> +
<input type="number" min="0" name="i2" value="0"> =
<output name="added">0</output>
</form>
Copy the code
You can read more about the output element:
output
The elementoutput
: HTML’s native live region element
What you don’t know:not()
The use of the function pseudo-class not() is described in detail in the article “A Primer on CSS selectors Level 4”.
Negative pseudo-class: Not () is a function pseudo-class that takes a list of selectors and represents elements that are not represented by their arguments. The :not() selector can be used as a selector for judgment, like not in JavaScript. Its main function is to strip out elements that conform to the rules and apply style rules to other elements. In fact, CSS Selector Level 3 already has :not(), but it has a weaker function, such as :not(p) to select elements that are not
. In the new version, however, it is more powerful and can apply more complex rules, but again does not allow nested use, such as :not(:not(…) ).
When developing projects, we often have lists with a margin-bottom between the items and want to leave the margin-bottom out of the last item. For example, something like this:
If we want to avoid multiple classes, we can concatenate them, because :not() has no logical combinator operation, so we can do this:
body:not(.home):not(.away):not(.page-50) {
}
Copy the code
A few days ago @Zhang Xinxu teacher in the “CSS: NOT pseudo-class may be wrong understanding” article also elaborated that we use :not() easy to mistake a few points. For example, it is not clear about its priority, does not support complex selectors, easy to understand the negative logic relationship, etc.
Removes the last character from the string
There are two ways to remove the last character from a string in JavaScript:
// use 'slice' let input = "w3cplus.com" function removeLastCharacter(STR){let charcter_arr = str.split("); return charcter_arr.slice(0, charcter_arr.length - 1).join(''); } let output = removeLastCharacter(input); console.log(`Output is ${output}`); // let input = "w3cplus.com" function removeLastCharacter(STR){return str.substring(0, str.length - 1); } let output = removeLastCharacter(input); console.log(`Output is ${output}`); // => Output is w3cplus.coCopy the code
A few giFs to help you better understand the properties of the CSS Grid
These two years there is a discussion about CSS Grid Layout in the community is very popular. Powerful enough to add just one line of code to a responsive layout (for some specific scenarios).
This line of code is:
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
Copy the code
Repeat (), auto-fit, Minmax () and FR are used in the code. Here are a few giFs from the @per article to show you what they can do:
<! -- HTML --> <div class="container"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> </div> // CSS .container { display: grid; grid-template-columns: 100px 100px 100px; grid-template-rows: 50px 50px; }Copy the code
See the following effect:
Replace 100px with 1fr:
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 50px 50px;
}
Copy the code
The effect is as follows:
Use repeat() to make the code cleaner:
.container {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-template-rows: repeat(2, 50px);
}
Copy the code
Use auto-fit for auto-fill:
.container {
display: grid;
grid-gap: 5px;
grid-template-columns: repeat(auto-fit, 100px);
grid-template-rows: repeat(2, 100px);
}
Copy the code
Adding minmax() to a single line of code in some scenarios can achieve this responsiveness:
.container {
display: grid;
grid-gap: 5px;
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
grid-template-rows: repeat(2, 100px);
}
Copy the code
For more information about repeat(), auto-fit, Minmax (), and FR, read:
- CSS Grid brings new units: fractional units
fr
minmax()
How the function works- Intrinsically Responsive CSS Grid with
minmax()
andmin()
- Auto-Sizing Columns in CSS Grid:
auto-fill
vsauto-fit
summary
The article focuses on Top 10 Most Deadly CSS Mistakes Made by New and Experienced Developers by @Bill Mei. The output element of HTML can be used to represent the calculation result of the application or the result of the user operation. CSS :not() does not have a logical character, but can be combined with multiple operators to achieve a similar effect. Finally, several GIFs made by @per simply and roughly tell us how to use REPEAT (), FR, auto-fit and Minmax () in CSS Grid Layout to achieve a responsive effect with one line of code. Often used in list layout scenarios.
Finally, I hope you enjoy this episode. If you have a better suggestion or related accumulation, please share it with us in the comments below.