There are always ups and downs in a person's life. It will not always rise like the rising sun, nor will it always be miserable. Repeated ups and downs are training for a person. Therefore, those who are floating above do not need to be proud; those who are sinking below do not need to be pessimistic. We must be frank and humble, optimistic and enterprising, and move forward. ——Konosuke Matsushita
Hello everyone, my name is Jiang Chen. In today's Internet environment, everyone must have felt it to some extent. In this impetuous society, only by constantly maintaining one's character can one perceive different gains and encourage each other.
A collection of the latest interview questions in 2023, so be prepared at all times.
This article was first published on WeChat public account: Wild Programmer Jiang Chen
Everyone is welcome to like, collect and follow
Article list
- 2023 front-end interview questions - JS
- 2023 front-end interview questions - coding chapter
- 2023 front-end interview questions - HTML
- 2023 front-end interview questions - React
- 2023 front-end interview questions - Vue chapter
How is CSS selector priority calculated?
The browser uses priority rules to determine which styles an element displays. Priority is determined through 4 dimensional indicators. We assume that they are a、b、c、d
named after , which respectively represent the following meanings:
a
Indicates whether to use inline style. 1 if used,a
0 otherwise.b
Represents the number of ID selectors.c
Represents the sum of the number of class selectors, attribute selectors and pseudo-class selectors.d
Represents the sum of label (type) selectors and pseudo-element selectors.
The result of the priority is not to generate a score from the above four values, but to compare each value separately. a、b、c、d
The weights decrease from left to right. When judging the priority, compare one by one from left to right until the maximum value is found, then stop. So, if b
the values of are different, then c
and d
will have no effect on the result no matter how large they are. For example 0,1,0,0
, has a higher priority than 0,0,10,10
.
When priorities are equal, the style rule that appears latest will be adopted. If you write the same rules in a style sheet (either within this file or in another style file), the style that appears last (at the bottom of the file) has higher priority and will be adopted.
When writing styles, I use a lower priority so that they can be easily overridden. It is especially important when writing UI components, so that users do not need to !important
override the style of the component through very complicated priority rules or usage methods.
What is the difference between resetting CSS and normalizing CSS? Which way would you choose and why?
- Resetting : Resetting means removing all browser default styles. For all elements on the page, styles such as margin, padding, and font-size are all set the same. You will have to redefine the styles of various elements.
- Normalizing : Normalizing does not remove all default styles, but retains useful parts and corrects some common errors.
When I need to implement a very personalized web design, I will choose the reset method, because I have to write a lot of custom styles to meet the design needs, and then the standardized default styles are no longer needed.
Please explain how Float positioning works.
Float is a CSS positioning property. Floated elements are removed from the normal flow of the web page, but retain some fluidity, affecting the positioning of other elements (such as text surrounding the floated element). This is different from absolute positioning, where absolutely positioned elements are completely detached from the document flow.
clear
Use the CSS property left、right、both
to move the element down (clear the float) below the floated element.
If the parent element contains only floated elements, the height of the parent element will collapse to 0. We can fix this by clearing the float from after the floated element to before the parent element is closed.
There is a hack method, which is to customize a .clearfix
class and use a pseudo-element selector ::after
to clear the float. There are also some methods, such as adding empty <div></div>
and setting overflow
the attribute of the floated element's parent element. Different from these methods, clearfix
this method only needs to add a class to the parent element, which is defined as follows:
.clearfix::after {
content: '';
display: block;
clear: both;
}
It is worth mentioning that setting the parent element attribute to overflow: auto
or overflow: hidden
will cause its internal child elements to form a block formatting context (Block Formatting Context), and the parent element will expand itself so that it can surround its child elements.
Please explain the z-index attribute and explain how to form a stacking context.
The property in CSS z-index
controls the vertical stacking order of overlapping elements. z-index
Can only affect elements whose position
value is not static
.
Without z-index
a value defined, elements are stacked in the order they appear in the DOM (lower levels appear higher up). Non-statically positioned elements (and their children) will always override statically positioned elements, regardless of HTML hierarchy.
A stacking context is an element that contains a set of layers. In a set of cascading contexts, z-index
the values of its child elements are set relative to the parent element rather than the document root. Each stacking context is completely independent of its sibling elements. If element B is on top of element A, element C will never be on top of element B, even if element C, a child of element A, has a higher z-index value than element B.
Each stacking context is self-contained: when an element's content is stacked, the entire element is stacked sequentially within the parent stacking context. A few CSS properties will trigger a new cascading context, for example, opacity is less than 1, filter is not none, and transform is not none.
Each stacking context is self-contained: when an element's content is stacked, the entire element is stacked sequentially within the parent stacking context. A few CSS properties trigger a new cascading context, such as opacity
less than 1, filter
no none
, transform
no none
.
Please explain the Block Formatting Context and how it works.
The block formatting context (BFC) is the visual CSS rendering part of the Web page. It is the area where block-level box layout occurs and where floated elements interact with other elements.
An HTML box (Box) that meets any of the following conditions will create a block formatting context:
- The value of float is not none.
- The value of position is not static or relative.
- The value of display is table-cell, table-caption, inline-block, flex, or inline-flex.
- The value of overflow is not visible.
In BFC, the left outer edge of each box touches the left edge of its containing block.
The vertical margins of two adjacent block-level boxes will collapse.
What are the techniques for clearing floats and what situations are they applicable to?
- Empty div method: 。
- Clearfix method: Using the .clearfix class has been mentioned above.
- overflow: auto or overflow: hidden method: already mentioned above.
In large projects, I use the Clearfix method where needed .clearfix
. The method of setting overflow: hidden
may cause its child elements to be displayed incompletely when the height of the child element is greater than the parent element.
Please explain what are sprites (css sprites) and how to implement them?
Sprite map, also called sprite map. Because the English name of the common carbonated drink Sprite is also Sprite, some people also use the informal translation of Sprite.
A sprite is a picture that combines multiple pictures into one. It is used on many websites that use a lot of small icons (Gmail is using it). Implementation:
- Use a generator to package multiple images into a sprite and generate appropriate CSS for it.
- Each image has a corresponding CSS class that defines the
background-image
,background-position
andbackground-size
properties. - When using images, add the corresponding class to your element.
benefit:
- Reduce the number of HTTP requests to load multiple images (one sprite only requires one request). But with HTTP2, loading multiple images is no longer a problem.
- Load resources in advance to prevent problems caused by starting to download when needed. For example, pictures that only appear in the :hover pseudo-class will not flicker.
How to solve the style compatibility problem of different browsers?
- After you determine the cause of the problem and the problematic browser, use a separate style sheet that is only loaded by the problematic browser. This approach requires the use of server-side rendering.
- Use a library that already handles this kind of problem, such as Bootstrap.
- Use autoprefixer to automatically generate CSS property prefixes.
- Use Reset CSS or Normalize.css.
How to serve pages to browsers with limited functionality? What technologies and processes are used?
- Graceful downgrade: Build your app for modern browsers while ensuring it runs correctly in older browsers.
- Progressive enhancement: Build apps based on the user experience, but add new features as browsers support them.
- Use caniuse.com to check feature support.
- Use autoprefixer to automatically generate CSS property prefixes.
- Feature detection using Modernizr.
Is there any different way to hide the content (making it only available to screen readers)?
These methods are related to accessibility (a11y).
- width: 0; height: 0: Makes the element not occupy any space on the screen, causing it not to be displayed.
- position: absolute; left: -99999px: Place it off the screen.
- text-indent: -9999px: This only applies to text within block elements.
- Metadata: For example by using Schema.org, RDF and JSON-LD.
- WAI-ARIA: A W3C technical specification on how to increase the accessibility of web pages.
Even if WAI-ARIA were the ideal solution, I would go with the absolute positioning method because it has minimal caveats, works for most elements, and is very simple to use.
Are you familiar with making SVG?
Yes, you can color shapes (including specifying properties on objects) using inline CSS, embedded CSS sections, or external CSS files. Most SVG on the web uses inline CSS, but each type has advantages and disadvantages.
Basic shading operations can be accomplished by setting the fill
and properties. You can set the color of the interior, and you can set the color of the lines drawn around it. You can use the same CSS color naming scheme as used in : color name (i.e. ), RGB value (i.e. ), hexadecimal value, RGBA value, and so on.stroke
fill
stroke
HTML
red
rgb(255,0,0)
<rect
x="10"
y="10"
width="100"
height="100"
stroke="blue"
fill="purple"
fill-opacity="0.5"
stroke-opacity="0.8"
/>
What should you pay attention to when writing efficient CSS?
First, the browser matches from the rightmost selector, the key selector, to the left. According to the key selector, the DOM
browser filters out the elements, and then traverses the parent elements of the selected elements upward to determine whether there is a match. The shorter the selector matching statement chain, the faster the browser will match it. Avoid using tags and universal selectors as key selectors because they will match a large number of elements and the browser must do a lot of work to determine whether the parents of these elements match.
In principle, BEM (Block Element Modifier) recommends naming independent CSS classes, and when a hierarchical relationship is required, the relationship is also reflected in the naming, which naturally makes the selector efficient and easy to override.
Figure out which CSS properties trigger reflow, repaint, and compositing. When writing styles, avoid triggering the possibility of relayout.
What are the advantages and disadvantages of using CSS preprocessing?
advantage
- Improve CSS maintainability.
- Easy to write nested selectors.
- Introduce variables and add theme functions. Theme files can be shared across different projects.
- Generate duplicate CSS via mixins.
- Split the code into multiple files. Although CSS without preprocessing can be split into multiple files, multiple HTTP requests need to be made to load these files.
shortcoming
- Preprocessing tools are required.
- Recompile time can be slow.
Describe pseudo-elements and their uses.
CSS pseudo-elements are keywords added to selectors to select specific parts of an element. They can be used for decoration ( :first-line
, :first-letter
) or to add elements to markup (combined with content:...) without having to modify the markup ( :before
, :after
).
- :first-line and :first-letter can be used to modify text.
- In the .clearfix method mentioned above, use clear: both to add elements that do not take up space.
- Use :before and after to display the triangular arrow in the prompt. Encourages separation of concerns because triangles are considered part of the style, not the real DOM. It is not possible to draw a triangle using only CSS styles without using additional HTML elements.
Talk about your understanding of the box model and how to tell the browser to use a different box model to render the layout.
The CSS box model describes a rectangular box generated from elements in the document tree and laid out according to a typography pattern. Each box has a content area (e.g. text, image, etc.) and optional surrounding padding
, border
and margin
areas.
The CSS box model is responsible for calculating:
- How much space does a block-level element take up.
- Whether borders overlap and margins merge.
- The size of the box.
The box model has the following rules:
- The size of block-level elements is determined by
width
,height
,padding
,border
andmargin
. - If not specified
height
, the height of a block-level element is equal to the content height of its containing child elements plus the content heightpadding
(unless there are floated elements, see below). - If not specified
width
, the width of a non-floated block-level element is equal to the width of its parent element minus the parent element's widthpadding
. - The element's is calculated
height
from the content's .height
- The element's is calculated
width
from the content's .width
- By default,
padding
and are not part ofborder
the elementswidth
and .height
* { box-sizing: border-box; } What effect will it produce?
- The element is applied by default
box-sizing: content-box
, and the width and height of the element will only determine the size of the content. box-sizing: border-box
Change the way the elementswidth
and are calculated so that the size of and will also be taken into account.height
border
padding
- The height of the element = the height of the content + the vertical padding + the width of the vertical border
- The width of the element = the width of the content + the horizontal padding + the width of the horizontal border
What are the attribute values of display?
none
, block
, inline
, inline-block
, table
, table-row
, table-cell
, list-item
.
What is the difference between inline and inline-block?
I added block to it for better comparison.
block | inline-block | inline | |
---|---|---|---|
size | Fills the width of its parent container. | Depends on the content. | Depends on the content. |
position | Starts on a new line and is not allowed to have HTML elements next to it (unless it is float ) |
Flows with other content and allows other elements to sit alongside it. | Flows with other content and allows other elements to sit alongside it. |
Is it possible to set width andheight |
able | able | cannot. The setting will be ignored. |
vertical-align Alignment can be used |
Can't | Can | Can |
Margins and padding | exists in all directions | exists in all directions | Only the horizontal direction exists. Vertical directions are ignored. Although border and padding are content around , the vertical space depends on'line-height' |
float | - | - | Just like an block element, vertical margins and padding can be set. |
What are the differences between relative, fixed, absolute and static positioning?
The attribute value of a positioned element position
must be relative
, absolute
, fixed
or sticky
.
-
static
:Default positioning attribute value. This keyword specifies that the element uses normal layout behavior, that is, the element's current layout position in the normal flow of the document. At this time the top, right, bottom, left and z-index properties are invalid. -
relative
: Under this keyword, the element is first placed at the position when no positioning is added, and then the position of the element is adjusted without changing the page layout (therefore, a blank will be left at the position where the element was without positioning). -
absolute
: No space is reserved for the element, and the position of the element is determined by specifying the offset of the element relative to the nearest non-statically positioned ancestor element. Absolutely positioned elements can have margins set and will not be merged with other margins. -
fixed
: Do not reserve space for the element, but specify the element position by specifying the element's position relative to the screen viewport (viewport). The element's position does not change when the screen scrolls. When printing, the element will appear at a fixed location on each page. The fixed attribute creates a new stacking context. When the transform attribute of an element's ancestor is non-none, the container is changed from the viewport to that ancestor. -
sticky
: The box position is calculated based on the normal flow (this is called the position in normal flow), and then positioned relative to the element's flow root (BFC) and containing block (nearest block-level ancestor element) in the flow. In all cases (even when the positioned element istable
), the positioning of this element does not affect subsequent elements. When element B is sticky positioned, the position of subsequent elements is still determined based on the position of B when it is not positioned.position: sticky
The effect on table elements isposition: relative
the same as .
Do you know CSS Flexbox and Grid?
learn. Flexbox is mainly used for one-dimensional layout, while Grid is used for two-dimensional layout.
Flexbox solves many common problems in CSS, such as vertical centering of elements in containers, sticky footers, etc. Bootstrap and Bulma are based on Flexbox, which is the recommended way to create layouts. I've used Flexbox before, but flex-grow
ran into some browser incompatibility issues (Safari) when using it, and I had to inline-blocks
rewrite my code using and manually calculate the percentage width, which wasn't a great experience.
Grid
Creating grid-based layouts is by far the most intuitive way (preferably!), but browser support is currently not widespread.
Please explain the difference between responsive and mobile-first when writing a website.
Note that these two methods are not mutually exclusive.
Making a website responsive means that the website will automatically adjust the size and functionality of some elements based on the size of the device screen, usually the viewport width via CSS media queries, for example, making fonts smaller on small screens.
@media (min-width: 601px) {
.my-class {
font-size: 24px;
}
}
@media (max-width: 600px) {
.my-class {
font-size: 12px;
}
}
The mobile-first strategy also refers to responsiveness, but it suggests that we should define all styles for mobile devices by default and only add specific rules to adapt to other devices. Here is the former example:
.my-class {
font-size: 12px;
}
@media (min-width: 600px) {
.my-class {
font-size: 24px;
}
}
A mobile-first strategy has 2 major advantages:
- There is better performance on mobile devices because the rules applied to them do not require validation against any media queries.
- It lets you force writing cleaner code related to responsive CSS rules.
What is the difference between responsive design and adaptive design?
Both responsive design and adaptive design aim to improve the user experience across different devices, and are optimized and adjusted based on parameters such as window size, resolution, usage environment, and control methods.
The adaptability principle of responsive design: The website should have good display and usability effects on various devices with one code. Responsive websites create a great user experience by using media queries, adaptive grids, and responsive images to change based on a variety of factors. Just like a ball expands and contracts to fit different sized hoops.
Adaptive design is more like the modern interpretation of progressive enhancement. Unlike responsive design, which simply adapts, adaptive design selects the most appropriate functions and layout from a predefined series of window sizes and other characteristics by detecting device and other characteristics. Instead of using one ball to go through various hoops, the adaptive design allows multiple balls to be used and then the most appropriate one is selected based on different hoop sizes.
Under what circumstances should you use translate() instead of absolute positioning? When, the opposite is true.
translate()
is transform
a value of . Changing transform
or opacity
will not trigger a browser reflow or repaint, only compositions. Changing absolute positioning will trigger relayout, which in turn triggers redrawing and compounding. transform
Causes the browser to create a GPU layer for the element, but changing the absolute positioning uses the CPU. Therefore, it translate()
is more efficient and can shorten the drawing time of smooth animation.
When using translate()
, the element still occupies its original space (sort of position:relative
), unlike changing absolute positioning.