Frontend Interview Knowledge Collection - CSS
CSS Interview Knowledge Summary
1. Introduce the standard CSS box model? How is the low-version IE box model different?
Related knowledge points:
(1) There are two box models: IE box model (border-box) and W3C standard box model (content-box)
(2) The box model consists of four parts: content, padding, margin, border
Difference between IE box model and W3C standard box model:
(1) W3C standard box model: width and height properties only include content, not border and padding
(2) IE box model: width and height properties include content, border, and padding, referring to content
+padding+border.
In IE8+ browsers, which box model to use can be controlled by box-sizing (a new CSS property). The default value is content-box, which is the standard box model.
If box-sizing is set to border-box, the IE box model is used. In IE6, 7, 8, if DOCTYPE is missing, the box model will be interpreted as IE box model.
If DOCTYPE is declared in the page, all browsers will interpret the box model as the W3C box model.
Answer:
The box model consists of four parts: margin, border, padding, and content.
The difference between the standard box model and the IE box model lies in the range corresponding to width and height. The width and height properties of the standard box model
only include content, while the width and height properties of the IE box model include border, padding, and content.
Generally, we can change the element's box model by modifying the box-sizing property.
Detailed references: 《CSS 盒模型详解》
2. What are CSS selectors?
(1) ID selector (#myid)
(2) Class selector (.myclassname)
(3) Tag selector (div,h1,p)
(4) Descendant selector (h1 p)
(5) Child selector (ul>li)
(6) General sibling selector (li~a)
(7) Adjacent sibling selector (li+a)
(8) Attribute selector (a[rel="external"])
(9) Pseudo-class selector (a:hover,li:nth-child)
(10) Pseudo-element selector (::before, ::after)
(11) Universal selector (*)
3. What’s the difference between double colon and single colon in ::before and :after? Explain the role of these 2 pseudo-elements.
Related knowledge points:
Single colon (:) is used for CSS3 pseudo-classes, double colon (::) is used for CSS3 pseudo-elements. (Pseudo-elements consist of double colon and pseudo-element name)
Double colon was introduced in the current specification to distinguish pseudo-classes from pseudo-elements. However, browsers need to simultaneously support older existing pseudo-element syntax,
such as :first-line, :first-letter, :before, :after, etc.
New pseudo-elements introduced in CSS3 no longer support the old single colon syntax.
Use ::before to insert content before other content, otherwise use ::after.
In code order, content generated by ::after comes after content generated by ::before.
From a stacking perspective, content generated by ::after will be on top of content generated by ::before.
Answer:
In CSS3, single colons represent pseudo-classes and double colons represent pseudo-elements. However, for compatibility with existing pseudo-element syntax, some browsers also support single colons
for pseudo-elements.
Pseudo-classes generally match special states of elements, such as hover, link, etc., while pseudo-elements generally match special positions, such as after, before, etc.
4. Difference between pseudo-classes and pseudo-elements
CSS introduced the concepts of pseudo-classes and pseudo-elements to format information outside the document tree. That is, pseudo-classes and pseudo-elements are used to modify parts that are not in the document tree, such as the
first letter of a sentence, or the first element in a list.
Pseudo-classes are used to add corresponding styles when an existing element is in a certain state, which changes dynamically based on user behavior. For example, when a user hovers over a specified
element, we can use :hover to describe this element's state.
Pseudo-elements are used to create elements that are not in the document tree and add styles to them. They allow us to set styles for certain parts of an element. For example, we can use ::be
fore to add some text before an element and add styles to this text. Although users can see these texts, they are actually not in the document tree.
Sometimes you'll find pseudo-elements use two colons (::) instead of one colon (:). This is part of CSS3 and attempts to distinguish pseudo-classes from pseudo-elements. Most browsers
support both values. According to the rules, (::) should be used instead of (:) to distinguish pseudo-classes from pseudo-elements. However, because the older W3C specification did not specifically distinguish
this, most browsers currently support both ways of representing pseudo-elements.
Detailed references: 《总结伪类与伪元素》
5. Which properties in CSS can be inherited?
Related information:
The overview of each CSS property definition indicates whether the property is inherited by default or not. This determines how to calculate the value when you don't specify a value for an element's property.
When an inherited property of an element is not specified, it takes the computed value of the same property from the parent element. Only the document root element takes the initial value given in the property's overview (which should be the default value in the property's own definition).
When a non-inherited property (sometimes called reset property in Mozilla code) of an element is not specified, it takes the property's initial value
(which is specified in the property's overview).
Inherited properties:
(1) Font family properties
font, font-family, font-weight, font-size, font-style, font-variant, font-stretch, font-size-adjust
(2) Text series properties
text-indent, text-align, text-shadow, line-height, word-spacing, letter-spacing,
text-transform, direction, color
(3) Table layout properties
caption-side, border-collapse, empty-cells
(4) List properties
list-style-type, list-style-image, list-style-position, list-style
(5) Cursor property
cursor
(6) Element visibility
visibility
(7) Some less common ones: speak, page, quotes (sets the quotation type for nested citations), etc.
Note: When a property is not an inherited property, you can use the inherit keyword to specify that a property should inherit its value from the parent element. The inherit keyword is used to explicitly
specify inheritance and can be used for any inheritable/non-inheritable property.
Answer:
Each property definition indicates whether the property is inheritable. An inheritable property, when not specified, uses the value of the same property from the parent element
as its own value.
Generally, inheritable properties include font-related properties like font-size and font-weight, text-related properties like color and text-align,
some table layout properties, list properties like list-style, cursor property, element visibility.
When a property is not an inheritable property, we can also make it inherit by setting its value to inherit to get the same-named property value from the parent element.
Detailed references: 《继承属性》 《CSS 有哪些属性可以继承?》
6. How is the CSS priority algorithm calculated?
Related knowledge points:
CSS priority is determined based on the specificity value of style declarations.
The specificity value of selectors is divided into four levels, as follows:
(1) Inline style 1,0,0,0
(2) ID selector 0,1,0,0
(3) Class selector / attribute selector / pseudo-class selector 0,0,1,0
(4) Element and pseudo-element selector 0,0,0,1
Calculation method:
(1) The initial value of each level is 0
(2) The superposition of each level is the sum of the number of occurrences of the selector
(3) No carrying, e.g., 0,99,99,99
(4) Represented as: 0,0,0,0
(5) No correlation between counts at each level
(6) Level judgment is from left to right. If a digit value is the same, judge the next digit
(7) If two priorities are the same, the one that appears later has higher priority. !important also applies
(8) The specificity value of the universal selector is: 0,0,0,0
(9) Inherited styles have the lowest priority. Universal selector styles have higher priority than inherited styles
(10) !important (weight) has no specificity value, but its priority is the highest. For easy memory, it can be considered as having a specificity value of 1,0,0,0,0.
Calculation examples:
(1) #demo a{color: orange;}/*specificity value: 0,1,0,1*/
(2) div#demo a{color: red;}/*specificity value: 0,1,0,2*/
Note:
(1) When applying styles, CSS first checks the weight of the rule (!important). Rules with weight have the highest priority. When the weight is the same, compare the specificity of the rules.
(2) Declarations with larger specificity values have higher priority.
(3) For declarations with the same specificity value, the rule declared later has higher priority (closest to the element's appearance)
(4) Some browsers have carry-over issues due to byte overflow, which is not considered here.
Answer:
When determining priority, we first check whether a property declaration has weight, i.e., whether !important is added after the declaration. If a declaration has weight,
its priority is the highest, provided that no declaration with the same weight appears later. If the weight is the same, we need to compare the specificity of the matching rules.
A matching rule is generally composed of multiple selectors. The specificity of a rule is the accumulated specificity of its constituent selectors. The specificity of selectors can be divided into four levels:
the first level is inline style, at 1000; the second level is ID selector, at 0100; the third level is class selector, pseudo-class selector, and attribute selector, at 0010;
the fourth level is element selector and pseudo-element selector, at 0001. Each time a selector appears in a rule, its specificity is added. This addition is limited to the corresponding level
and does not carry over. The comparison of selector specificity values is sorted from left to right, meaning specificity values starting with 1 are larger than all specificity values starting with 0.
For example, a rule with specificity value 1000 has higher priority than a rule with specificity value 0999. If two rules have equal specificity values, the one that appears later has the highest priority.
For combined declarations specificity value calculation, refer to: 《CSS 优先级计算及应用》 《CSS 优先级计算规则》 《有趣:256 个 class 选择器可以干掉 1 个 id 选择器》
7. Explanation of the LVHA pseudo-class order?
The a tag has four states: link unvisited, link visited, mouse hover, and active, corresponding to four pseudo-classes: :link, :visited, :hover, :active.
When the link is unvisited:
(1) When the mouse hovers over the a link, both :link and :hover states are active. To change the a tag's color, the :hover pseudo-class must be declared after the :link pseudo-class.
(2) When the mouse clicks to activate the a link, all three states :link, :hover, :active are active. To display the a tag's active style (:active),
:active must be declared after :link and :hover. Hence the LVHA order.
When the link is visited, the situation is basically the same, except :link needs to be replaced with :visited.
Can this order be changed? Yes, but only :link and :visited can swap positions, because a link is either visited or unvisited, they cannot be simultaneously satisfied,
so there's no issue of overriding.
8. What new pseudo-classes are added in CSS3?
(1) elem:nth-child(n) selects the nth child element under the parent element, and this child element's tag name is elem. n can accept specific numbers
or functions.
(2) elem:nth-last-child(n) same as above, but counting from the end.
(3) elem:last-child selects the last child element.
(4) elem:only-child selects if elem is the only child element under the parent element.
(5) elem:nth-of-type(n) selects the nth elem type element under the parent element. n can accept specific numbers or functions.
(6) elem:first-of-type selects the first elem type element under the parent element.
(7) elem:last-of-type selects the last elem type element under the parent element.
(8) elem:only-of-type selects if there is only one elem type element among the parent element's children.
(9) elem:empty selects elem type elements that contain no child elements or content.
(10) elem:target selects the current active elem element.
(11) :not(elem) selects every element that is not an elem element.
(12) :enabled controls the enabled state of form controls.
(13) :disabled controls the disabled state of form controls.
(14) :checked selects radio buttons or checkboxes that are checked.
Detailed references: 《CSS3 新特性总结(伪类)》 《浅谈 CSS 伪类和伪元素及 CSS3 新增伪类》
9. How to center a div?
- Horizontal centering: Set a width for the div, then add margin:0 auto
div {
width: 200px;
margin: 0 auto;
}
- Horizontal centering using text-align:center
.container {
background: rgba(0, 0, 0, 0.5);
text-align: center;
font-size: 0;
}
.box {
display: inline-block;
width: 500px;
height: 400px;
background-color: pink;
}
- Centering an absolutely positioned div
div {
position: absolute;
width: 300px;
height: 300px;
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-color: pink; /* for visual effect */
}
- Horizontal and vertical centering method one
/* For a container with known width and height (500x300), set layer margin: */
div {
position: absolute;
width: 500px;
height: 300px;
top: 50%;
left: 50%;
margin: -150px 0 0 -250px; /* margin is half of its own width and height */
background-color: pink;
}
- Horizontal and vertical centering method two
/* For unknown container width and height, use the transform property */
div {
position: absolute; /* either relative or absolute positioning */
width: 500px;
height: 300px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: pink;
}
- Horizontal and vertical centering method three
/* Using flex layout, consider compatibility in actual use */
.container {
display: flex;
align-items: center;
justify-content: center;
}
.container div {
width: 100px;
height: 100px;
background-color: pink;
}
- Horizontal and vertical centering method four
/* Using text-align:center and vertical-align:middle */
.container {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0, 0, 0, 0.5);
text-align: center;
font-size: 0;
white-space: nowrap;
overflow: auto;
}
.container::after {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
.box {
display: inline-block;
width: 500px;
height: 400px;
background-color: pink;
white-space: normal;
vertical-align: middle;
}
Answer:
Common methods for centering include:
For elements with fixed width and height:
(1) Use margin:0 auto for horizontal centering.
(2) Use absolute positioning, set all four directions to 0, and set margin to auto. Since width and height are fixed, the corresponding directions are evenly divided, achieving both horizontal
and vertical centering.
(3) Use absolute positioning, first position the element's top-left corner to the page center using top:50% and left:50%, then adjust the element's
center to the page center using negative margin.
(4) Use absolute positioning, first position the element's top-left corner to the page center using top:50% and left:50%, then adjust the element's
center to the page center using translate.
(5) Use flex layout, set the container's vertical and horizontal centering with align-items:center and justify-content:center,
then its child elements can also be vertically and horizontally centered.
For elements with unknown width and height, the last two methods above can achieve vertical and horizontal centering.
10. What values does display have? Explain their roles.
block Block type. Default width is parent element's width, can set width and height, displays on a new line.
none Element does not display and is removed from the document flow.
inline Inline element type. Default width is content width, cannot set width and height, displays on the same line.
inline-block Default width is content width, can set width and height, displays on the same line.
list-item Displays like a block-type element and adds a list-style marker.
table This element displays as a block-level table.
inherit Specifies that the value of the display property should be inherited from the parent element.
Detailed references: 《CSS display 属性》
11. What are the positioning origins for relative and absolute position values?
Related knowledge points:
absolute
Generates an absolutely positioned element, positioned relative to the padding box of the first parent element whose position value is not static. It can also be understood as positioning relative to the top-left corner of the padding box of the nearest parent element with position set to absolute or relative.
fixed (not supported in older IE)
Generates an absolutely positioned element, positioned relative to the browser window.
relative
Generates a relatively positioned element, positioned relative to its normal position in the document flow.
static
Default value. No positioning, the element appears in the normal flow (ignoring top, bottom, left, right, z-index declarations).
inherit
Specifies that the value of the position property should be inherited from the parent element.
Answer:
A relatively positioned element is positioned relative to its own normal position.
An absolutely positioned element is positioned relative to the padding box of its first ancestor element whose position value is not static. We can understand this as: first find an ancestor element of the absolutely positioned element whose position value is not static, then position relative to that ancestor element's padding box. When calculating the positioning distance, the padding value is also included.
12. What new features does CSS3 have? (Answer based on project)
Various new CSS selectors (:not(.input): all nodes whose class is not "input")
Rounded corners (border-radius: 8px)
Multi-column layout
Shadows and reflection (Shadow/Reflect)
Text effects (text-shadow)
Text rendering (Text-decoration)
Linear gradients (gradient)
Transform
Scaling, positioning, skewing, animation, multiple backgrounds
For example: transform: scale(0.85, 0.90) translate(0px, -30px) skew(-9deg, 0deg), Animation
13. Please explain CSS3 Flexbox (flexible box layout model) and its applicable scenarios?
Related knowledge points:
Flex is short for Flexible Box, meaning "flexible layout", providing maximum flexibility for box models.
Any container can be designated as a Flex layout. Inline elements can also use Flex layout. Note that after setting Flex layout, the child elements' float, clear, and vertical-align properties will be invalidated.
Elements using Flex layout are called Flex containers. All their child elements automatically become container members, called Flex items.
The container has two axes by default: the horizontal main axis and the vertical cross axis. Items are arranged along the main axis by default.
The following 6 properties are set on the container:
flex-direction determines the direction of the main axis (i.e., the arrangement direction of items).
flex-wrap defines how to wrap if an axis line cannot fit all items.
flex-flow is a shorthand for flex-direction and flex-wrap, with a default value of row nowrap.
justify-content defines the alignment of items on the main axis.
align-items defines how items are aligned on the cross axis.
align-content defines the alignment of multi-line axes. If there is only one axis, this property has no effect.
The following 6 properties are set on items:
order defines the order of items. Smaller values are placed first, default is 0.
flex-grow defines the enlargement ratio of an item, default is 0 (no enlargement even if there's remaining space).
flex-shrink defines the shrinkage ratio of an item, default is 1 (item shrinks if space is insufficient).
flex-basis defines the main axis space an item occupies before distributing extra space. Default is auto, i.e., the item's original size.
flex is a shorthand for flex-grow, flex-shrink, and flex-basis, with a default value of 0 1 auto.
align-self allows individual items to have a different alignment from other items, overriding the align-items property. Default is auto, inheriting the parent element's align-items property, or stretch if there is no parent element.
Answer:
Flex layout is a new layout method added in CSS3. We can make an element a flex container by setting its display property to flex, and all its child elements become its items.
A container has two axes by default: a horizontal main axis and a vertical cross axis perpendicular to the main axis. We can use flex-direction to specify the direction of the main axis.
We can use justify-content to specify the arrangement of items on the main axis, and align-items to specify the arrangement on the cross axis. We can also
use flex-wrap to specify the wrapping behavior when items don't fit on one line.
For items in the container, we can use the order property to specify their arrangement order. We can use flex-grow to specify the enlargement ratio when there's remaining space,
and flex-shrink to specify the shrinkage ratio when space is insufficient.
Detailed references: 《Flex 布局教程:语法篇》 《Flex 布局教程:实例篇》
14. What’s the principle of creating a triangle with pure CSS?
/* Uses the principle of equal division at the junction of adjacent borders.
Set the element's width and height to 0, only set borders,
hide any three sides (set color to transparent), and the remaining one forms a triangle. */
#demo {
width: 0;
height: 0;
border-width: 20px;
border-style: solid;
border-color: transparent transparent red transparent;
}
15. How to design a full-screen Pi-shaped layout?
Simple approach:
The top div has width: 100%,
The bottom two divs each have width: 50%,
Use float or inline to prevent line breaks.
16. How to implement multi-column equal height in CSS?
(1) Use the characteristic that padding-bottom and margin-bottom with positive and negative values offset each other without affecting page layout. Set the parent container to overflow: hidden.
This way, the parent container's height is still the height of the columns without padding-bottom. When any column's height increases,
the parent container's height is stretched to the height of the tallest column. Other shorter columns use their padding-bottom to compensate for the height difference.
(2) Use the characteristic that all table-cell elements have equal height to implement multi-column equal height.
(3) Use the flex layout feature where the align-items property defaults to stretch. If items have no height set or are set to auto, they will fill the container's entire height,
implementing multi-column equal height.
Detailed references: 《前端应该掌握的 CSS 实现多列等高布局》 《CSS:多列等高布局》
17. What browser compatibility issues are often encountered? Causes, solutions, and common hack techniques?
(1) PNG24 images show background issues in IE6
Solution: Make them PNG8, or use a script to handle it.
(2) Different browsers have different default margin and padding values
Solution: Add a global *{margin:0;padding:0;} to unify.
(3) IE6 double margin bug: In IE6, if you set float on an element and also set margin-left or margin-right, the margin value doubles.
#box{float:left;width:10px;margin:0 0 0 10px;}
In this case, IE produces a 20px distance.
Solution: Add _display:inline; to the floated element's style to convert it to an inline property. (This symbol is only recognized by IE6)
(4) Progressive recognition approach, gradually excluding parts from the whole.
First, cleverly use "\9" to separate IE browsers from all others.
Then, use "+" to further separate IE8, IE7, and IE6, isolating IE8.
.bb{
background-color:#f1ee18;/*All browsers recognize*/
.background-color:#00deff\9;/*IE6,7,8 recognize*/
+background-color:#a200ff;/*IE6,7 recognize*/
_background-color:#1e0bd1;/*IE6 recognize*/
}
(5) In IE, you can use conventional property access methods to get custom properties, and also use getAttribute() to get custom properties. In Firefox, you can only use getAttribute() to get custom properties.
Solution: Use getAttribute() uniformly to get custom properties.
(6) In IE, the event object has x, y properties but no pageX, pageY properties. In Firefox, the event object has pageX, pageY properties but no x, y properties.
Solution: (Conditional comments) Disadvantage: may add extra HTTP requests in IE browsers.
(7) In Chrome's Chinese interface, text smaller than 12px is forcibly displayed at 12px by default.
Solution:
1. Add CSS property -webkit-text-size-adjust:none; but this no longer works in Chrome version 27 and above.
2. Use -webkit-transform:scale(0.5); note that -webkit-transform:scale(0.75); shrinks the entire span, so you need to convert the span to a block element using display:block/inline-block/...;
(8) After clicking a visited link, the hover style no longer appears.
Solution: Change the CSS property order to L-V-H-A
(9) Quirks mode issue: Missing DTD declaration. Firefox still parses in standards mode, but IE triggers quirks mode. To avoid unnecessary trouble from quirks mode, it's best to develop the habit of writing DTD declarations.
18. What causes invisible blank gaps between li elements? How to fix?
Browsers render whitespace characters (spaces, newlines, tabs, etc.) between inline elements as a single space. For aesthetics, we often put each <li> on a new line,
which creates newline characters between <li> elements, becoming a space that occupies one character width.
Solutions:
(1) Set float:left for <li>. Disadvantage: Some containers cannot use float, such as image carousels with left/right navigation.
(2) Put all <li> elements on the same line. Disadvantage: Code looks messy.
(3) Set the character size within <ul> to 0, i.e., font-size:0. Disadvantage: Other character sizes within <ul> are also set to 0, requiring additional resetting of other character sizes, and Safari still shows gaps.
(4) Eliminate character spacing in <ul> with letter-spacing:-8px. Disadvantage: This also sets character spacing for <li> content, so you need to reset character spacing for <li> content to default letter-spacing:normal.
Detailed references: 《li 与 li 之间有看不见的空白间隔是什么原因引起的?》
19. Why initialize CSS styles?
-Because of browser compatibility issues, different browsers have different default values for some tags. Without CSS initialization, page display differences between browsers often occur.
-Of course, initializing styles can have some impact on SEO, but you can't have both. The goal is to minimize the impact while initializing.
Simplest initialization method: *{padding:0;margin:0;} (strongly not recommended)
Taobao's style initialization code:
body,h1,h2,h3,h4,h5,h6,hr,p,blockquote,dl,dt,dd,ul,ol,li,pre,form,fieldset,legend,button,input,select,textarea,th,td{margin:0;padding:0;}
body,button,input,select,textarea{font:12px/1.5tahoma,arial,\5b8b\4f53;}
h1,h2,h3,h4,h5,h6{font-size:100%;}
address,cite,dfn,em,var{font-style:normal;}
code,kbd,pre,samp{font-family:couriernew,courier,monospace;}
small{font-size:12px;}
ul,ol{list-style:none;}
a{text-decoration:none;}
a:hover{text-decoration:underline;}
sup{vertical-align:text-top;}
sub{vertical-align:text-bottom;}
legend{color:#000;}
fieldset,img{border:0;}
button,input,select,textarea{font-size:100%;}
table{border-collapse:collapse;border-spacing:0;}
20. What is a containing block? Understanding of containing block?
A containing block is a box used by an element for calculation and positioning.
(1) The root element (often considered as <html>) is called the "initial containing block", and its size equals the browser's viewport size.
(2) For other elements, if the element's position is relative or static, the "containing block" is formed by the content box boundary of its nearest block container ancestor.
(3) If an element's position is fixed, the "containing block" is the "initial containing block."
(4) If an element's position is absolute, the "containing block" is established by the nearest ancestor whose position is not static. The specific method is:
If the ancestor element is a pure inline element, the rules are slightly more complex:
• Assume an inline box with width 0 is generated before and after the inline element. Then the enclosing box outside the padding boxes of these two inline boxes is the inline element's "containing block".
• If the inline element is split across lines, the "containing block" is undefined, meaning CSS2.1 specification doesn't define it clearly, and browsers implement it themselves.
Otherwise, the "containing block" is formed by the padding box boundary of that ancestor.
If there is no qualified ancestor element, the "containing block" is the "initial containing block."
21. What is the collapse value of the visibility property used for? How does it differ across browsers?
(1) For regular elements, it behaves the same as visibility: hidden; The element is invisible but still occupies page space.
(2) But for table-related elements like table rows, table groups, table columns, table column groups, it behaves like display: none, meaning the occupied space is also released.
Differences across browsers:
In Chrome, using the collapse value has no difference from using the hidden value.
In Firefox, Opera, and IE11, using the collapse value works as its name suggests: table rows disappear, and the next row fills their position.
Detailed references: 《CSS 里的 visibility 属性有个鲜为人知的属性值:collapse》
22. Difference between width:auto and width:100%
Generally speaking:
width:100% makes the element box's width equal to the parent element's content box width.
width:auto makes the element fill the entire parent element. The margin, border, padding, and content areas automatically allocate horizontal space.
23. Difference between percentage calculation for absolute and non-absolutely positioned elements
The width and height percentages for absolutely positioned elements are calculated relative to the padding box of the nearest ancestor with position not static.
The width and height percentages for non-absolutely positioned elements are calculated relative to the parent element's content box.
24. Briefly introduce the advantages and disadvantages of using base64 encoded images.
Base64 encoding is an image processing format. It encodes an image into a long string through a specific algorithm. When displaying on a page, this string can replace the image's
url attribute.
Advantages of using base64:
(1) Reduces one HTTP request for an image.
Disadvantages of using base64:
(1) According to base64's encoding principle, the encoded size is about 1/3 larger than the original file. Encoding large images into HTML/CSS not only increases file size,
affecting loading speed, but also increases the browser's parsing and rendering time for HTML or CSS files.
(2) Base64 cannot be cached directly. Only the files containing base64, such as HTML or CSS, can be cached. This is much less effective than directly caching images.
(3) Compatibility issues: IE8 and earlier browsers do not support it.
Generally, small icons on some websites can be introduced using base64 images.
Detailed references: 《玩转图片 base64 编码》 《前端开发中,使用 base64 图片的弊端是什么?》 《小 tip:base64:URL 背景图片与 web 页面性能优化》
25. Interrelationship between ‘display’, ‘position’, and ‘float’?
(1) First, determine if the display property is none. If so, the position and float property values don't affect the element's final appearance.
(2) Then determine if the position value is absolute or fixed. If so, the float property is invalid, and the display value should be
set to table or block. The specific conversion depends on the initial conversion value.
(3) If the position value is not absolute or fixed, determine if the float property value is none. If not, the display
value is converted according to the above rules. Note that if position is relative and float exists, relative positioning
is relative to the final position after floating.
(4) If float is none, determine if the element is the root element. If so, the display property is converted according to the above rules. If not,
keep the specified display property value unchanged.
Overall, it can be seen as a priority-like mechanism: "position:absolute" and "position:fixed" have the highest priority. When they exist,
float doesn't work, and 'display' values need adjustment. Next, when the element's 'float' value is not "none" or it's the root element,
adjust the 'display' value. Finally, for non-root, non-floating, non-absolutely positioned elements, the 'display' property value remains as set.
Detailed references: 《position 跟 display、margincollapse、overflow、float 这些特性相互叠加后会怎么样?》
26. Understanding margin collapsing
Related knowledge points:
The top margin (margin-top) and bottom margin (margin-bottom) of block-level elements sometimes merge into a single margin. This phenomenon is called "margin
merging."
Prerequisites for collapsing: margins must be adjacent!
According to W3C specification, two margins are adjacent when the following conditions are met:
• They must be block-level boxes in the normal document flow (non-float and non-absolutely positioned) and within the same BFC.
• No line boxes, no clearance, no padding, and no borders separating them.
• Both belong to vertically adjacent margins, which can be any of the following:
• An element's margin-top and the margin-top of its first child in normal flow
• An element's margin-bottom and the margin-top of its next sibling in normal flow
• An element's margin-bottom (with height: auto) and the margin-bottom of its last child in normal flow
• An element with height 0 and min-height 0, no children in normal flow, and not establishing a new BFC, its margin-top
and margin-bottom
3 scenarios for margin collapsing:
(1) Adjacent sibling element margin collapsing.
Solution:
• Set one element to create a block formatting context (BFC)
(2) Margin collapsing between parent and first/last child.
Solution:
For margin-top collapsing, perform one of the following (any one condition is sufficient):
• Set the parent element as a block formatting context element;
• Set border-top on the parent element;
• Set padding-top on the parent element;
• Add an inline element between the parent and first child for separation.
For margin-bottom collapsing, perform one of the following (any one condition is sufficient):
• Set the parent element as a block formatting context element;
• Set border-bottom on the parent element;
• Set padding-bottom on the parent element;
• Add an inline element between the parent and last child for separation;
• Set height, min-height, or max-height on the parent element.
(3) Margin collapsing of empty block-level elements.
Solution:
• Set vertical border;
• Set vertical padding;
• Add an inline element inside (just pressing Space won't work);
• Set height or min-height.
Answer:
Margin collapsing refers to the vertical overlapping of margins between two adjacent elements.
Generally, it can be divided into four cases:
First, the marin-bottom and margin-top values of adjacent sibling elements collapse. In this case, we can solve it by setting one element as a BFC.
Second, the margin-top of the parent element and the margin-top of the child element collapse. They collapse because they are adjacent, so we can
solve this by setting border-top or padding-top on the parent element to separate them, or we can set the parent element as a BFC.
Third, the margin-bottom of the parent element (with height: auto) and the margin-bottom of the child element collapse. They collapse because they are
adjacent and the parent element's height is not fixed. So we can set border-bottom or padding-bottom on the parent element to separate them, or set
a height, max-height, or min-height on the parent element. Setting the parent element as a BFC is the simplest method.
Fourth, the margin-top and margin-bottom of an empty element (with no content) collapse. We can solve this by setting border, padding, or height.
27. Understanding the BFC specification (block formatting context)?
Related knowledge points:
Block Formatting Context (BFC) is part of the visual CSS rendering of web pages. It is the area where block-level boxes are generated during layout and also the interaction limit area for floating elements and other elements.
In simple terms:
• BFC is an independent layout environment. It can be understood as a container where items are arranged according to certain rules and do not affect items in other environments.
• If an element meets the conditions for triggering BFC, the layout of elements inside the BFC is not affected by external elements.
Creating BFC:
(1) Root element or element containing the root element
(2) Floating elements: float = left|right|inherit (≠ none)
(3) Absolutely positioned elements: position = absolute|fixed
(4) display = inline-block|flex|inline-flex|table-cell|table-caption
(5) overflow = hidden|auto|scroll (≠ visible)
Answer:
BFC stands for block formatting context. Once an element forms a BFC, the layout generated by its internal elements does not affect external elements, and the layout of external elements
does not affect the internal elements of the BFC. A BFC is like an isolation area, mutually non-interfering with other areas.
Generally, the root element is a BFC area. Floating and absolutely positioned elements also form BFCs. Elements with display values of inline-block, flex, etc.
also create BFCs. Additionally, elements with overflow values other than visible create BFCs.
Detailed references: 《深入理解 BFC 和 MarginCollapse》 《前端面试题-BFC(块格式化上下文)》
28. What is IFC?
IFC stands for inline formatting context, with the following layout rules:
(1) Boxes inside an inline context are placed horizontally, one after another.
(2) When one line is not enough, it automatically wraps to the next line.
(3) The height of the inline context is determined by the height of the tallest inline box inside.
Detailed references: 《[译]:BFC 与 IFC》 《BFC 和 IFC 的理解(布局)》
29. Please explain why we need to clear floats? Methods to clear floats
Floating elements can move left or right until they encounter another floating element or the containing box's outer edge. Floating boxes do not belong to the normal flow in the document. When an element floats,
it does not affect the layout of block-level elements, only inline elements. At this point, the normal flow in the document behaves as if the floating box doesn't exist. When the containing box's
height is less than the floating box, "height collapse" occurs.
Clearing floats is to eliminate the impact of using floating elements. The height of floated elements collapses, and this height collapse prevents proper display of the page layout.
Methods to clear floats:
(1) Use the clear property to clear floats. Refer to 28.
(2) Use BFC (block formatting context) to clear floats. Refer to 26.
Because BFC elements do not affect external elements, BFC elements can also be used to clear the impact of floats. If not cleared, child element floats cause parent element
height collapse, which inevitably affects the layout and positioning of subsequent elements, violating the BFC's characteristic of child elements not affecting external elements.
30. Principle of using the clear property to clear floats?
The clear property is used to clear floats with the following syntax:
clear: none|left|right|both
If we take the literal meaning, clear:left should mean "clear left float", and clear:right should mean "clear right float". However, this interpretation is
incorrect because the float is still there, not cleared.
The official explanation of the clear property is: "The element box's edge cannot be adjacent to preceding floating elements." We set the clear property on an element to avoid the influence of floating elements
on that element, not to clear the float.
One more thing to note: the clear property means the element box's edge cannot be adjacent to preceding floating elements. Note the word "preceding," meaning the clear
property has no effect on "following" floating elements. Considering that the float property is either left or right, and cannot be both at the same time, since the clear
property ignores "following" floating elements, when clear:left is effective, clear:right must be ineffective. At this time, clear:left
is equivalent to setting clear:both. Similarly, if clear:right is effective, it's also equivalent to setting clear:both. This shows that clear:left and cle
ar:right declarations are practically useless, at least in the CSS world. Just use clear:both directly.
Commonly, pseudo-elements are used to clear floats:
.clear::after {
content: '';
display: table; // or 'block', or 'list-item'
clear: both;
}
The clear property is only effective on block-level elements, while ::after pseudo-elements are inline by default. This is why we need to set the display property when using pseudo-elements to clear floats.
31. The principle of zoom:1 in clearing floats?
Clears floats by triggering hasLayout.
The zoom property is unique to IE browsers. It sets or retrieves the zoom ratio of an object. It's used to solve some quirky bugs in IE, such as margin
overlapping, float clearing, and triggering IE's hasLayout property.
The general background is:
After setting the zoom value, the element expands or shrinks, and the height and width are recalculated. Changing the zoom value triggers re-rendering.
This principle is used to solve the problem where the parent element doesn't automatically expand when child elements float in IE.
The zoom property is unique to IE browsers and is not supported by Firefox and older WebKit-based browsers. However, zoom is now gradually being
standardized, appearing in the CSS3.0 specification draft.
Currently, non-IE browsers don't support this property. What do they use to scale elements? They can use the animation property scale in CSS3 for scaling.
32. Have you used media queries in mobile layout?
Suppose you are reading this article on a display device, and you also want to project it on a screen or print it out. Display devices, screen projections, and printing all have
their own characteristics. CSS provides methods for adapting documents to display on different media.
When a media query is true, the related stylesheet or style rules are applied following the normal cascade rules. When a media query returns false, the stylesheet with the media query will still be
downloaded (but not applied).
It contains a media type and at least one expression using media properties such as width, height, and color to limit the scope of the stylesheet. The media query added in CSS3 allows making styles
applicable to certain specific device ranges without modifying the content.
Detailed references: 《CSS3@media 查询》 《响应式布局和自适应布局详解》
33. Do you use CSS preprocessors? Which one do you like?
SASS (no essential difference between SASS and LESS, just because the team frontend uses SASS)
34. CSS optimization and performance improvement methods?
Loading performance:
(1) CSS compression: package and compress the written CSS, which can significantly reduce its size.
(2) Single CSS properties: when you need bottom and left margins, many people choose margin:top 0 bottom 0; but margin-bottom: bottom; margin-left: left; is more efficient.
(3) Reduce use of @import, and recommend using link instead, because the latter loads the page simultaneously, while the former loads after the page finishes loading.
Selector performance:
(1) Key selector: the last part of the selector is the key selector (used to match the target element). CSS selectors are matched from right to left. When using a descendant selector, the browser traverses all child elements to determine if they are the specified element, etc.
(2) If a rule has an ID selector as its key selector, don't add a tag to the rule. Filter out irrelevant rules (so the style system doesn't waste time matching them).
(3) Avoid using universal rules like *{} which require astronomical calculations! Only select the elements you need.
(4) Select as few tags as possible, and use class instead.
(5) Use descendant selectors as little as possible to reduce selector weight. Descendant selectors have the highest cost. Keep selector depth to a minimum, no more than
three levels deep, and use classes to associate each tag element.
(6) Know which properties can be inherited and avoid repeatedly specifying rules for these properties.
Rendering performance:
(1) Use high-performance properties carefully: float, positioning.
(2) Minimize page reflow and repaint.
(3) Remove empty rules: {}. Empty rules are generally created to reserve styles. Removing these empty rules can reduce CSS document size.
(4) When the property value is 0, don't add units.
(5) When the property value is a floating-point decimal 0.**, you can omit the 0 before the decimal point.
(6) Standardize various browser prefixes: vendor-prefixed properties first, standard properties after.
(7) Don't use the @import prefix; it affects CSS loading speed.
(8) Optimize selector nesting and try to avoid deep nesting.
(9) CSS sprites: combine small icons in the same area of a page for easy use and reducing page request count. But this also increases image size. Consider the pros and cons before use.
(10) Use the display property correctly. Some style combinations become ineffective due to display, unnecessarily increasing style size while affecting parsing performance.
(11) Don't overuse web fonts. Web fonts may be unfamiliar for Chinese websites but are popular abroad. Web fonts are usually large, and some
browsers block page rendering while downloading web fonts, harming performance.
Maintainability and robustness:
(1) Extract styles with the same properties, integrate them, and use class in the page to improve CSS maintainability.
(2) Separate style and content: define CSS code in external CSS.
Detailed references: 《CSS 优化、提高性能的方法有哪些?》 《CSS 优化,提高性能的方法》
35. How does the browser parse CSS selectors?
The style system starts matching from the key selector and then moves left to find the ancestor elements of the rule selector. As long as the selector's subtree continues to work, the style system continues moving left
until it matches the rule or abandons the rule due to mismatch.
Imagine reading CSS rules from left to right: most rules are found to be mismatched only when read to the end (far right). This would be time-consuming and energy-intensive,
and many would be useless. If we adopt a right-to-left approach, as soon as the rightmost selector doesn't match, we can discard it directly, avoiding many invalid matches.
Detailed references: 《探究 CSS 解析原理》
36. Should we use odd or even font sizes on the web? Why?
(1) Even-numbered font sizes are relatively easier to form proportion relationships with other parts of web design. For example, when I use 14px for the body font size, I might use 14
× 0.5 = 7px margins in some places and 14 × 1.5 = 21px title font sizes in other places.
(2) Browser issue: older versions like IE6 forcibly convert odd-numbered fonts to even numbers, e.g., 13px rendered as 14px.
(3) System differences: in early Windows, SimSun (中易宋体) bitmap font only had 12, 14, 15, 16px sizes, notably missing 13px.
Detailed references: 《谈谈网页中使用奇数字体和偶数字体》 《现在网页设计中的为什么少有人用 11px、13px、15px 等奇数的字体?》
37. In what scenarios are margin and padding appropriate to use?
Margin is used to separate the spacing between elements; padding is used to separate the spacing between element and content.
Margin is used in layout to separate elements, making them independent from each other.
Padding is used for the spacing between element and content, creating a distance between content (text) and the (wrapper) element.
When to use margin:
• When you need to add whitespace outside the border
• When the whitespace doesn't need a background (color)
• When you want the whitespace between two vertically adjacent boxes to cancel each other out. E.g., 15px + 20px margins result in 20px of whitespace.
When to use padding:
• When you need to add whitespace inside the border
• When the whitespace needs a background (color)
• When you want the whitespace between two vertically adjacent boxes to be their sum. E.g., 15px + 20px padding results in 35px of whitespace.
38. How to extract style modules? Your ideas and practical experience? [Alibaba Fliggy interview question]
My understanding is to separate commonly used CSS styles into individual CSS files... Separate general styles from business-related ones. Make general ones into style modules for sharing, and put business-related ones
into business-related libraries as modules with corresponding functions.
Detailed references: 《CSS 规范-分类方法》
39. Briefly explain the CSS3 all property.
The all property is actually a shorthand for all CSS properties, meaning all CSS properties are set in a certain way, but not including the unicode-bidi and direction
CSS properties. It supports three CSS common property values: initial, inherit, unset.
initial means initial value. All CSS properties of the element except unicode-bidi and direction use the property's default initial
value.
inherit means inheritance. All CSS properties of the element except unicode-bidi and direction inherit the property values from the parent element.
unset means cancel settings. The current element's CSS set by the browser or user is ignored. Then, if it's an inheritable CSS property like color, use
the inherited value. If it's a non-inheritable CSS property like background-color, use the initial value.
Detailed references: 《简单了解 CSS3 的 all 属性》
40. Why is it not recommended to use universal selectors to initialize CSS styles?
Using *{padding:0;margin:0;} is simple to write, but it's a universal selector that needs to traverse all tags. When a website is large with many styles,
this approach significantly increases the website's load, causing long loading times. Therefore, large websites generally have a structured set of initialization styles.