Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to deeply parse the custom CSS reset style

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, I will talk to you about how to deeply analyze the custom CSS reset style, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.

Whenever I start a new project, the first task is to deal with the edges and corners of the CSS language. To solve these problems, a custom set of base styles is usually used.

For a long time in the past, I used the famous CSS reset style (CSS Reset) from Eric Meyer. As an ancient and practical piece of CSS code, it hasn't been updated in the past decade, and a lot of things have changed a lot during that time!

Recently, I started using the CSS reset style that I defined myself. It contains a number of tips I have summarized to improve both the user experience and the CSS development experience. We will introduce this custom CSS reset style. And in-depth study of each of the rules, in addition to discussing the role of each rule, but also a profound and simple analysis of the reasons for the use of the rule!

Background introduction

Historically, the main purpose of CSS reset styles has been to clear the default styles of browsers, thus ensuring style consistency between browsers. My CSS reset style is not intended to solve this problem.

Today, there is little difference in layout or spacing between different browsers. Overall, modern browsers, as we would expect, have faithfully implemented the CSS specification. Therefore, dealing with the issue of style consistency is no longer so important.

Also, I never thought it necessary to get rid of all the default styles in the browser. For example, I will use the label to set the font style to italic! Although different design specifications may have to be followed in different projects, I think it makes no sense to remove the common sense default setting.

My CSS reset style may not fit the classic definition of "CSS reset style", but on the other hand, this CSS reset style is also more creative.

My CSS Reset

Make less gossip and go straight to the code:

/ * 1. Use a more-intuitive box-sizing model.*/*, *:: before, *: after {box-sizing: border-box;} / * 2. Remove default margin*/* {margin: 0;} / * 3. Allow percentage-based heights in the application*/html, body {height: 100%;} / * Typographic tweaks! 4. Add accessible line-height 5. Improve text rendering*/body {line-height: 1.5;-webkit-font-smoothing: antialiased } / * 6. Improve media defaults*/img, picture, video, canvas, svg {display: block; max-width: 100%;} / * 7. Remove built-in form typography styles*/input, button, textarea, select {font: inherit;} / * 8. Avoid text overflows*/p, H2, h3, h4, h5, h6, h7 {overflow-wrap: break-word;} / * 9. Create a root stacking context*/#root, # _ next {isolation: isolate;}

Although the code is short, there is a lot of practical information in this small stylesheet. Let's get started!

1. Box-sizing box model

Before we begin, answer a question! What is the width of the .box element (the rectangular area of the pink border) in the following code without other CSS styles? Is it 200px, 240px, 244px or 0px?

.parent {width: 200px;} .box {width: 100%; border: 2px solid hotpink; padding: 20px;}

Width: 100% is set in the style of the .box element, and because its parent element .parent has a width of 200px, 100% here will be resolved to 200px.

So what does the width of the 200px do? By default, browsers apply this width to the content box (content box). As we all know, the "content box" here is what the box in the box model actually contains, which is inside border and padding:

Width: 100% sets the content part of the .box model to 200px, the inner margin padding increases the 40px width (20px on each side), and the border border increases the 4px (2px on each side). Through addition calculation, it is not difficult to find that the width of the pink border rectangle is 244px. Therefore, the answer to the above question is 244px.

When we try to stuff a 244px box into a 200px-wide parent container, it overflows:

This behavior seems strange, and we can change it with the following settings:

*, *:: before, *:: after {box-sizing: border-box;}

When this rule is applied, the percentage of width is resolved based on border-box. In the above example, our pink box is 200px, while the internal content-box will be reduced to 156px (200px-40px-4px).

In my opinion, this is an essential style rule because it makes CSS easier to use. We apply it to all elements and pseudo elements with a wildcard selector (*). Contrary to popular perception, this styling does not cause performance to deteriorate, as shown in the article * {Box-sizing: Border-box} FTW.

Inheriting box-sizing

I saw another style setting on the Internet:

Html {box-sizing: border-box;} *, *: before, *: after {box-sizing: inherit;}

This is a useful strategy if you want to migrate the use of border-box in an existing large project. If you start a whole new project from scratch, it's not necessary. For simplicity, I omitted it in the CSS reset style.

First, we can create a "legacy" selector to keep the value of box-sizing as content-box, which is also the default value of the box-sizing property:

.legacy {box-sizing: content-box;}

Then, when there is an application that has not yet migrated to use border-box, we can add the class to the corresponding location to keep the original style unaffected:

Why would you do that? Now, let's consider how the elements in this code snippet are calculated.

Legacy is assigned, so it uses box-sizing: content-box.

The style of its child elements is box-sizing: inherit. It will also be set to content-box because its parent element is set to content-box,nav.

The tag does not have legacy, so it inherits from its parent; it inherits from; has been set to border-box.

In essence, each element can obtain a box-sizing attribute from its parent element. If it has an ancestor with legacy set, its property value is content-box. Otherwise, it will eventually inherit from the tag with an attribute value of border-box.

two。 Remove the default value of margin * {margin: 0;}

Browsers make a lot of common-sense assumptions about margin. For example, H2 is larger than the margin of a paragraph by default. These assumptions are reasonable in documents that do word processing, but may not be accurate for modern web applications.

In addition, the outer margin will encounter the problem of outer margin collapse when you are not paying attention. It is really a nasty little clever devil. Also, I often find myself wanting elements without any margins by default. So I decided to get rid of it all.

When I do want to add margins to a specific tag, I can do it in a custom style in the project. The priority of the wildcard selector (*) is extremely low, and this rule can be easily overridden.

3. Based on the percentage of heighthtml, body {height: 100%;} copy code

We often use percentage to set height in CSS, but many times we find that it doesn't seem to work. Take a look at the following example:

Although the main element is set to height: 100%, the height of the element has not changed at all!

The reason why it doesn't work here is that in CSS streaming layout (the main layout mode in CSS), height and width work completely differently. The width of the element is calculated based on the parent element, and the height of the element is calculated based on its child elements. This topic is complicated, far beyond the scope of this article, and will not be discussed in this article.

In the following code example, when we apply the above rule to the code, we will find that the height of the main element has changed to 100%:

If you are using a JavaScript framework like React, you may also need to add a third selector to this rule: the root element used by the framework.

For example, in my Next.js project, the rules are updated as follows:

Html, body, # _ _ next {height: 100%;}

Why not use vh?

You might think: why do you have to use a percentage to set the height? Why not use vh instead?

The problem is that vh does not work properly on mobile devices; when the browser UI on the mobile device slides up and down, the visible part of the viewport adjusts, which causes the 100vh to be unstable in the browser and may exceed the actual use area of the screen.

In the future, the new CSS unit will solve this problem. Until then, I continue to use percentage-based heights.

4. Change line-heightbody {line-height: 1.5;}

The line height line-height controls the vertical spacing between each line of text in a paragraph. Its default value varies from browser to browser, but it is usually around 1.2. This unitary number is based on the ratio of font size. It functions like em. When line-height is 1.2, the line height of each line will be 20% larger than the font of the element.

Here is a problem. For those with dyslexia, these sentences are arranged too close together, making it more difficult to read. The WCAG standard stipulates that the row height should be at least 1.5.

Now, the number 1.5 affects headings (such as H2, H3, and so on) and other big font elements, resulting in considerable line spacing:

You may intuitively think of resetting the row height on the title. My understanding is that the WCAG standard is for "body" text, where only 1.5x lines are set for body.

Use "calc" to set up line-heights flexibly

I've been trying another way to set the row height, as follows:

* {line-height: calc (1em + 0.5rem);}

This is a fairly advanced code snippet, and although it is beyond the scope of this article, it will be briefly introduced here.

Instead of calculating the line height by multiplying the font size by a number like 1.5, this method uses the font size as the base and adds a fixed space for each line. For text paragraphs in body ((paragraphs)), each line is parsed to 24px (assuming the browser's default font size is used).

However, on larger text, this declaration produces tighter lines. The following example can be verified:

This needs to be used carefully. I am still experimenting with it at present.

One of the disadvantages is that we have to set it on all elements with * instead of applying it to body. This is because em units cannot be well inherited by child elements; it cannot cause each element to recalculate > calculate the value corresponding to 1em. For example, on this blog, my code was destroyed by third-party code because it assumed that line height was inheritable.

For more information about this technique, check out Kitty Giraudel's great blog post: using calc to calculate the Best Row height.

5. Set font-smoothingbody {- webkit-font-smoothing: antialiased;}

This CSS setting is a little controversial.

On MacOS computers, browsers use Sub-Pixel Anti-aliasing (subpixel antialiasing) by default. This technique uses R/G/B lights within each pixel to make the text easier to read.

In the past, this technology was thought to improve accessibility because it improved text contrast. You may have read a popular blog post to stop "fixing" font smoothing, which does not advocate switching to "antialiased".

The problem is that this article was written in 2012, when the high DPI "retina" showed that the time had not yet come. Today's pixels are even smaller and invisible to the naked eye. The physical layout of LED pixels has also changed. If you look at modern monitors under a microscope, you will no longer see an orderly grid of R/G/B lines.

In the 2018 release of MacOS Mojave, Apple disabled sub-pixel anti-aliasing in its operating system. I guess they realize that for modern hardware, this technology does more harm than good.

Confusingly, MacOS browsers like Chrome and Safari still use sub-pixel anti-aliasing by default. Therefore, we need to set-webkit-font-smoothing to antialiased to explicitly turn off sub-pixel anti-aliasing.

The difference between the two is:

MacOS is the only operating system that uses sub-pixel anti-aliasing, so this CSS rule has no impact on Windows, Linux, or mobile devices. If you are using a MacOS computer, you can try running the following code example:

6. Change the default values of media elements img, picture, video, canvas, svg {display: block; max-width: 100%;}

In CSS, images are considered "inline" inline elements, which means that they should be used in the middle of paragraphs like or as they should. This is inconsistent with the way we often use images. In general, we use pictures in the same way as paragraphs, headings, or sidebars, which are layout elements.

However, if we try to use inline elements in our layout, we will encounter strange things. For example, the problem of 4px white space of inline elements, this magical white space has something to do with line-height. By setting display:block on all images, we avoid this kind of problem.

I also set max-width: 100% to prevent large images from overflowing, especially if they are placed in a container that is not wide enough.

Most block-level elements automatically stretch / contract to fit their parent elements, but like

Such media elements are special: they are called replacement elements, and they do not follow the same rules.

If the "own" size of the image is 800 × 600, then

The width of the element will also be 800px, even if we put it in a parent element with 500px width.

This rule will prevent the image from exceeding its container, which I think is a wise thing to do.

7. The font of the form control inherits input, button, textarea, select {font: inherit;}

By default, buttons and input boxes do not inherit typesetting styles from their parents. On the contrary, they have their own weird style. For example, the system default Monospace font will be used. The text input box uses the system default sans-serif font. Both choose the microscopically-small font size (Chrome is 13.333px).

As you can imagine, it is very difficult to read 13px text on mobile devices. When we focus on the input box with a smaller font, the browser automatically zooms in to make the text easier to read.

Unfortunately, this kind of user experience is not good:

If you want to avoid this automatic scaling behavior, the font size entered must be at least 1rem/16px. There is one way to solve this problem:

Input, button, textarea, select {font-size: 1remt;}

This fixes the problem of automatic scaling, but it is only a stopgap measure. Let's solve this problem fundamentally: form input should not have its own typesetting style!

Input, button, textarea, select {font: inherit;}

Font is an abbreviation for CSS to set fonts. It sets a series of font-related properties, such as font-size, font-weight, and font-family. By setting its value to inherit, you can make these elements consistent with the typesetting in their surroundings.

As long as we don't use annoying smaller fonts in body, this solves all our problems at once.

8. Set text wrap p, H2, h3, h4, h5, h6, h7 {overflow-wrap: break-word;}

In CSS, if there is not enough space for all the characters in a line, the text will automatically wrap.

By default, the algorithm looks for "soft line wrapping" opportunities; these are where the algorithm can split characters. In English, the only opportunities for soft line wrapping are spaces and hyphens, but this varies from language to language.

If a line does not have any soft line wrapping opportunities and does not fit, it will cause text overflow:

This can lead to some annoying layout problems. Here, it adds a horizontal scroll bar. In other cases, it may cause the text to overlap with other elements or slide behind the image / video.

The overflow-wrap property allows us to adjust the line wrap algorithm and allow it to use hard line feeds when no soft line feeds are found:

Although hot, neither of these solutions is perfect, but at least hard line wrapping won't break the layout!

Thanks to Sophie Alpert for coming up with similar rules! She suggests applying it to all elements, which may be a good idea, but it's not something I've personally tested.

You can also try to add the hyphens attribute:

P {overflow-wrap: break-word; hyphens: auto;}

Hyphens: aut: automatically use hyphens (in languages that support them) to indicate hard line breaks. This also makes hard line-changing more common. If you have a very narrow text column, you can use it. Include it in my personal CSS reset style, but it's worth a try!

9. Root stack context # root, # _ _ next {isolation: isolate;}

The last one is optional. It is usually needed only if you are using a JavaScript framework such as React.

As we saw in piss off, z-index, the isolation property allows us to create a new stack context without setting the z-index.

This is useful because it allows us to ensure that certain high-priority elements (modes, drop-down lists, tooltips) always appear above other elements in the application. No strange stacking background errors, no endless z-index.

To match the framework you use, you need to adjust the selector according to your needs. We want to select the top-level elements that are rendered in the application. For example, it is used in create-react-app, so the correct selector is # root.

The final available code

Here is my CSS reset style, in a compact, replicable, graceful format:

/ * Josh's Custom CSS Reset https://www.joshwcomeau.com/css/custom-css-reset/*/*, *:: before, *: after {box-sizing: border-box;} * {margin: 0;} html, body {height: 100%;} body {line-height: 1.5;-webkit-font-smoothing: antialiased;} img, picture, video, canvas, svg {display: block; max-width: 100%;} input, button, textarea, select {font: inherit } p, h2, h3, h4, h5, h6, h7 {overflow-wrap: break-word;} # root, # _ _ next {isolation: isolate;}

Please feel free to copy / paste into your own project! There are no restrictions on its release (but I would appreciate it if you would like to keep a link to this post! ).

I didn't release this CSS reset style as a NPM package because I think you should have your own reset style. Bring it to your project and adjust it as you learn new things or discover new skills over time. If necessary, you can make your own NPM package at any time to facilitate reuse in the project.

After reading the above, do you have any further understanding of how to deeply parse the custom CSS reset style? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report