First, concept explanation
Defensive CSS, against whom? I sum it up: any situation in which performance or behavior deviates from its intended effect. The reason for these scenarios is the diversity of the end environment. Development and test cases can only cover most usage scenarios. In other environments, differences in parsing mechanisms, dynamic changes in content, and so on can lead to unexpected effects.
Second, the necessity of defense
Defensive CSS is not just about compatibility with a few other scenarios and avoiding boundary cases, but also about increasing the possibility of teamwork. Defensive CSS is similar in meaning to the JS try… Catch, it may not shorten the time of requirement development, but it is the last line of defense for the correct and stable operation of your program. Moreover, JS errors can only be perceived after user interaction, while CSS errors can be directly exposed to users, directly affecting user utilization rate and retention rate.
It is said that there are three programming styles: the run style, the neutral style, and the icing on the cake style. Can run line style represents: each set and judgment and when demand fit of joint, like the goat walking a tightrope, crumbling, but is not, had to be amazing, but this kind of style, not only for programmers highly demanding, and very conducive to teamwork, once unexpected accident to happen or demand change, is brought about by the avalanche of change; The rules of the moment style overview, the notes to write notes, the writing ideas of the place to write their reasons for doing so, the bottom treatment of the place to do interception processing, the robustness and maintainability of the program directly pull full; Foolproof style is more like Virgo, the pursuit of perfection and perfection, in the regular style to add a bright color, the young “Rebus” is a typical representative. The goal of defensive CSS is to technically change the programmer’s mind as much as possible and improve the usability and maintainability of projects. The goal can also be summed up as making your project work: run without mistakes, change without name-calling.
The role of defensive CSS is a backstop to conventional CSS, which is an important but easily overlooked part of achieving project stability.
Three, defense skills
Skill 1: Flex-wrap
Property background: Flex-wrap is a flex layout property that controls whether or not flex lines are folded when elements in a Flex container occupy more space than the flex container does.
Defense reason: The flex-wrap attribute does not fold by default, so it is easy to ignore the overflow of multiple elements. Flex-wrap: wrap;
Unintended consequences: internal elements being clipped, or scroll bars appearing in the Flex container;
Application Scenarios:
1) The Flex container has enough space in development, but the small screen will overflow;
2) The content is delivered by the server, and the number of elements cannot be prepaid in advance, which leads to scroll bars or internal elements being clipped in Flex container when it exceeds expectations;
Code:
.options-list {
display: flex;
flex-wrap: wrap;
}
Copy the code
The example scenario
Skill 2: Margin
Attribute Background: Margin adjusts the margin of an element. Used to specify the distance relationship between an element and the surrounding space.
Defense reasons: Prevent elements from squeezing space between elements, causing overlap, etc.
Unintended consequences: elements overlap or are squeezed;
Application Scenarios:
1) The space occupied by the content cannot ensure that there is no scene of extrusion with other elements;
Code:
.section__title {
margin-right: 1rem;
}
Copy the code
The example scenario
Skill 3: Long text processing
Background: How to display text when the length exceeds the container.
Unexpected consequences: Text breaks, style is not uniform;
Application Scenarios:
1) The list should be consistent but the text length is not controllable;
Assuming that the design is finally agreed upon and the excess is shown in omission, then the style code for the unexpected pocket is:
.username {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
Copy the code
Example scenario:
Skill 4: Prevent images from being stretched or compressed
Background: Usually, the size of the image sent by the server and the image uploaded by the user cannot be 100% consistent with the size of the container when displayed on the page, and it is inevitable that the image will be enlarged and shrunk.
Unintended consequences: images are stretched or compressed;
Application Scenarios:
1) The server sends pictures of various uncertain sizes;
2) Upload pictures by user customization and need to preview and edit;
.card__thumb {
object-fit: cover;
}
Copy the code
The demo link: monageju. Making. IO/Blog/object…
Example scenario:
Skill 5: Lock scrolling links
Background: Overscroll behavior is short for overscroll behavior-x and overscroll behavior-y, which controls the behavior of elements when they scroll to the edge. To put it more intelligibly: In the JS world, there is event bubbling mechanism, you can stop bubbling through the stopPropagation method of events. Similarly, in the CSS world, scrolling also has bubbling mechanism. When the inner element reaches the boundary, if it continues scrolling, it will drive the outer ancestor element to scroll, which is called scrolling chain. For easy memorization, you can also remember his image as a rolling bubble. The overscroll behavior property is just like the stopPropagation method of event to prevent bubbling events. It provides developers with the property to control whether the inner elements can “bubble” and drive the scroll of outer elements.
Unexpected consequences: “rolling bubbling” or “rolling penetration”;
Application Scenarios:
1) There are multiple scrolling elements on the page, and it is necessary to control separately whether each scrolling layer causes the outer scrolling;
.child {
overscroll-behavior-y: contain;
overflow-y: auto;
}
Copy the code
The demo link: monageju. Making. IO/Blog/oversc…
Scenario example: Such as demo link example
Development:
Now that we understand the function of the overscroll behavior property, let’s look at some expanded things:
First, let’s look at the property values of the overscroll behavior:
The overscroll behavior property has three values:
Auto – Default. Element scrolling is propagated to the ancestor element.
Contain – Prevents scrolling links. Scrolling does not propagate to ancestors, but shows native effects within elements. For example, the glare effect on Android or the bounce effect on iOS notifies the user when they touch the scroll boundary. Note: overscroll behavior: contain HTML elements to prevent scrolling navigation.
None – Like contain, but it also prevents the node from rolling itself (such as Android flash or iOS bounce).
There are two effects: the first is the drop-down refresh, and the second is the dazzle rebound. Here is a demo to see the effect: link portal
Drop-down refresh is native support function, if the project requires a custom dropdown refresh effect, in addition to consider how to implement the custom, but also how to get rid of the default native drop-down refresh, can appear otherwise the coexistence of two drop-down refresh, and remove the native drop-down refresh is also very simple, need only in the body or HTML element to add the following code:
Body {/* Disable the scroll bubble, but can still use the scroll refresh and dazzling-bounce effect and slide navigation */ overscroll behavior-y: contain; }Copy the code
To disable glare and bounce, apply the none attribute value of the overscroll behavior property as follows:
Body {/* Disable the default pull-down refresh and dazzle and bounce effects, but still allow scrolling */ overscroll-behavior-y: none; }Copy the code
In addition to the two effects described above, there is actually another effect: gesture navigation, such as swipe left to exit and swipe right to advance; To disable gesture navigation, use the following code:
Body {/* Disable sliding navigation */ overscroll-behavior-x: none; }Copy the code
Skill 6: CSS variable defaults
Background: CSS variables can achieve dynamic control of element attributes, but when CSS variables are undefined or invalid, resulting in variable value exceptions, at this point, the element style will be not expected, and variable default values can achieve exceptions, ensure that the page can still run when the variable value exception. As an additional note, alternate values are not intended for browser compatibility. If the browser does not support CSS custom properties, alternate values are of little use. It provides a backup mechanism only for browsers that support CSS custom properties. This mechanism works only if the given value is undefined or invalid. The first argument to the function is the name of the custom property. If a second parameter is provided, it represents an alternate value, which takes effect when the custom property value is invalid.
Unintended consequences: not displayed or deformed due to loss of width and height variable values;
Application Scenarios:
.item {
color: var(--my-var, red); /* Red if --my-var is not defined */
}
Copy the code
Skill 7: Elastic element size min-height/min-width
Background: When the requirement requires the complete display of a list data, but the space occupied by the list data cannot be fixed, elastic size min-* or Max -* can be used to avoid partial content too wide or too high to break through the fixed space and destroy the layout, which can automatically adapt to the problem of beautiful style caused by partial content occupying too large or too small space.
Unexpected consequences: occupying too much or too little space, damaging the layout or unattractive;
Application Scenarios:
.hero {
min-height: 350px;
}
Copy the code
Example scenario:
Max-width: 1em
If you use a fixed width for each element, an overflow will occur when the content space is larger than the container size. In this case, you need to use min-width to limit the minimum width, which can be automatically adapted when the size is exceeded.
Skill 8: Forgotten background-repeat
Background: Use the image as the background of the container. When the size of the container is larger than the image size, the default background will be repeated. If you ignore the above problems in development, the background will be repeated.
Example scenario:
Solutions:
The code is as follows:
background-image: url('.. '); background-repeat: no-repeat;Copy the code
Effect after solution:
Skill 9: Media query @media
Background: The use of media queries is more like CSS conditional judgment, which is based on the criteria you define. When the criteria are met, the style within the criteria takes effect.
For example: when the screen width is less than 600px, the body background color is red; When the screen width is between 600px and 800px, the body background color is yellow. When the screen width is greater than 800px, the background color of the body is blue.
Sample code:
/* Set the body's background color to blue */ body {background-color: blue; } / / @media screen and (max-width: 800px) {body {background-color: yellow; }} / / @media screen and (max-width: 600px) {body {background-color: red; }}Copy the code
The demo link is as follows: monageju. Dead simple. IO/Blog/media….
Skill 10: Text on pictures
Background: When the text needs to be displayed in the upper layer of the picture, if the picture fails to load and the background color of the outer container is close to the text color, the text display effect is not ideal;
For example, the container background is set to black, the image is orange, and the text color is nearly black. When the image fails to load, the text background color directly changes to the container background color, and the text and container background color coincide, as shown in the following example.
Effect after solution:
Solution code:
.card__img {
background-color: #FFF;
}
Copy the code
So far, even if the image fails to load, the problem on the image can still be displayed normally; As for the “broken picture” mark in the upper left corner when the picture fails to load, pseudo class can be used to block and beautify.
Skill 11: Use scroll bar properties wisely
Background: When the space of the container is fixed, if the content exceeds the container, in order to display all the content normally without expanding the space occupied, the overflow property will be used to control the automatic scrolling display of the excess part, and the scroll bar style will be given to indicate the remaining content. However, if this property is used improperly, the style will be very ugly.
For example, the overflow property has two similar property values, one is scroll and the other is auto. Both of these two attribute values can realize the scrolling display when the content is larger than the space occupied. The difference is that the scroll property will display the scroll bar regardless of whether the content is beyond the container space, while the auto property will distinguish the condition, and the scroll bar will be displayed when the content is beyond the container space, and the scroll bar will be hidden automatically when the content is beyond the container space, which is beautiful in style.
Solution code:
.box {
overflow-y: auto;
}
Copy the code
Example scenario:
Skill 12: Reserve space for scroll bars to avoid rearrangement
Background: Follow skill 11, will overflow: Auto be all right when we use it correctly? Not really.
Consider this scenario: There is a container box with a width of 100vw and a height of 100vh, in which commodity cards are displayed. When sliding to the bottom of the page, sliding loading will be triggered. When lazy loading is triggered, the height occupied by commodity cards in the container has exceeded 100vh. The appearance of the scrollbar makes the page have to give a certain width to the scrollbar. In this switching scene, the width of the outermost element changes due to the position of the scrollbar, resulting in the effect of rearrangement. Is it possible to avoid unnecessary rearrangement? The answer is yes.
You must remember that there are two very similar instructions in Vue: V-if and V-show. What are the principles and differences between them? In what situations are they used? By the way, do you have an idea? If not, then it doesn’t matter, then tip a little bit, since want to avoid redundant a rearrangement, and sliding load is inevitable, if I start to reserve the position of the scroll bar, but you can’t see, when the scroll bar should appear again let you see, can avoid unnecessary rearrangement? Now think again, is this how the V-show directive was designed?
CSS has a scrollbar-gutter property that does this when set to stable:
.box {
scrollbar-gutter: stable;
}
Copy the code
For example:
The scroll bar space is reserved when the content is short, and the scroll bar is displayed when the content exceeds;
Skill 13: Maximum picture width
Background: When setting a background image for a fixed width and height container, the image will overflow if the size of the background image exceeds the height and width of the container. Therefore, it is best to initialize the background image in the project’s resetCss with the following properties:
img{
max-width: 100%;
object-fit: cover;
}
Copy the code
Example:
Skill 14: Sticky positioning
Note: The sticky positioning of position refers to that the position attribute of an element switches between position:relative and position:fixed through user scrolling. This is handy for scenarios that require rolling ceilings; It is a typical example to promote the development of CSS technology based on business scenarios.
Skill 15: Browser Compatibility Do not batch process the CSS
Note: According to the W3C standard, batch groups select selectors. If one of the groups is invalid, the whole selector will be invalidated. Therefore, when encountering browser-compatible attributes, do not write in batches;
Example:
There is no problem with the selector if it is written as follows, because all selectors of the grouping selector are valid:
h1, h2, h3 { font-family: sans-serif }
Copy the code
In this case, it is equivalent to:
h1 { font-family: sans-serif }
h2 { font-family: sans-serif }
h3 { font-family: sans-serif }
Copy the code
But it is different if:
input::-webkit-input-placeholder,
input:-moz-placeholder {
color: #222;
}
Copy the code
This selector uses a group selector. In a certain browser, only one of the group selectors is valid, while the other choices are invalidated. According to the rule, the whole group selector will be invalidated.
input::-webkit-input-placeholder {
color: #222;
}
input:-moz-placeholder {
color: #222;
}
Copy the code
At this point, the effect is in line with the expected.
Four, conclusion
Generally, the stability of a project refers to the stability of the logical layer and the stability of the service layer, CSS is extremely easy to ignore a layer; When an online fault occurs in a project, the logical layer and the server can use log query and packet capture to locate the fault. However, it is difficult to quickly and accurately locate the CSS fault based on experience and the running environment of the project. When building stability, CSS should be written in a defensive way to avoid unexpected boundary situations as much as possible, which is the real value of defensive CSS.
If you get something, give it a thumbs up