Organize 45 CSS basic interview questions (with answers)

1. Introduce the standard CSS box model? How is it different from the box model of lower versions of IE?

Standard box model: width = content width (content) + border + padding + margin
Low version IE box model: width = content width (content + border + padding) + margin

2. The box-sizing property?

The parsing mode of the box model used to control the element, the default is content-box
context-box: W3C standard box model, set the height/width property of the element to refer to the height/width of the content part
border-box: IE traditional box model . Setting the height/width property of an element refers to the height/width of the border + padding + content part

3. What are CSS selectors? Which properties can be inherited?

CSS selectors: id selector (#myid), class selector (.myclassname), tag selector (div, h1, p), adjacent selector (h1 + p), child selector (ul > li), Descendant selector (li a), wildcard selector (*), attribute selector (a[rel=”external”]), pseudo-class selector (a:hover, li:nth-child)

Inheritable properties: font-size, font-family, color

Non-inheritable styles: border, padding, margin, width, height

Priority (proximity principle): !important > [ id > class > tag ]
!important has higher priority than inline

4. How is the CSS priority algorithm calculated?

Element selector: 1
class selector: 10
id selector: 100
Element label: 1000

  1. The style declared by !important has the highest priority, and is calculated if there is a conflict.

  2. If the priority is the same, the style that appears last is selected.

  3. Inherited styles have the lowest priority.

5. What are the new pseudo-classes in CSS3?

p:first-of-type selects the first element that belongs to its parent
p:last-of-type selects the last element that belongs to its parent
p:only-of-type selects the only element that belongs to its parent
p:only- child selects the only child element that belongs to its parent element
p:nth-child(2) selects the second child element that belongs to its parent element
:enabled :disabled The disabled state of the form control.
:checked The radio or checkbox is checked.

6. How to center the div? How to center a floated element? How to center an absolutely positioned div?

div:

border: 1px solid red;
margin: 0 auto;
height: 50px;
width: 80px;

Center the top, bottom, left, and right of the floating element

border: 1px solid red;
float: left;
position: absolute;
width: 200px;
height: 100px;
left: 50%;
top: 50%;
margin: -50px 0 0 -100px;

Absolute positioning left and right center:

border: 1px solid black;
position: absolute;
width: 200px;
height: 100px;
margin: 0 auto;
left: 0;
right: 0;

There is a more elegant way to center is to use flexbox

7. What are the values ​​of display? Explain their role?

inline (default) – inline
none – hide block –
block display
table – table display
list-item – item list
inline-block

8. What is the value of position?

static (default): Arrange according to the normal document flow;
relative (relative positioning): do not deviate from the document flow, refer to its own static position through top, bottom, left, right positioning;
absolute (absolute positioning): refer to the closest one not to The static parent element is positioned by top, bottom, left, right;
fixed (fixed positioning): the fixed reference object is the visible window.

9. What are the new features of CSS3?

  1. RGBA and transparency

  2. background-image background-origin(content-box/padding-box/border-box) background-size background-repeat

  3. word-wrap (Wrap for long indivisible words) word-wrap: break-word

  4. Text-shadow: text-shadow: 5px 5px 5px #FF0000; (horizontal shadow, vertical shadow, blur distance, shadow color)

  5. font-face property: define your own font

  6. Rounded corners (border radius): The border-radius property is used to create rounded corners

  7. Border image: border-image: url(border.png) 30 30 round

  8. Box Shadow: box-shadow: 10px 10px 5px #888888

  9. Media query: define two sets of css, which will use different properties when the size of the browser changes

10. Please explain CSS3's flexbox (flexible box layout model) and its applicable scenarios?

The purpose of this layout model is to provide a more efficient way to lay out, align, and allocate space for items in a container. In the traditional layout method, the block layout is to arrange the blocks in the vertical direction from top to bottom; and the inline layout is to arrange the blocks in the horizontal direction. The flexbox layout has no such inherent orientation constraints and can be freely manipulated by the developer.
Trial scenario: Elastic layout is suitable for mobile front-end development, and it is also perfectly supported on Android and ios.

11. What is the principle of creating a triangle with pure CSS?

First, you need to set the width and height of the element to 0. Then set the border style.

width: 0;
height: 0;
border-top: 40px solid transparent;
border-left: 40px solid transparent;
border-right: 40px solid transparent;
border-bottom: 40px solid #ff0000;

12. How to design a full-screen character layout?

The first real character:

  1. The height and width of the three blocks are determined;

  2. The above piece is centered with margin: 0 auto;

  3. The following two blocks do not wrap with float or inline-block;

  4. Adjust the position with margin to center them.

The second full-screen font layout:
the upper div is set to 100%, the lower div is 50% wide, and then use float or inline to make it not wrap.

13. Common compatibility issues?

  1. The default margin and padding of the labels of different browsers are different. *{margin:0;padding:0;}

  2. IE6 double margin bug: After the block attribute label is float, when there is a horizontal margin, the margin displayed in IE6 is larger than the set value. hack: display: inline; converts it to an inline property.

  3. The way of progressive identification, gradually exclude the part from the whole. First, the clever use of the "9" mark separates IE from all situations. Next, use "+" again to separate IE8 from IE7 and IE6, so that IE8 has been independently recognized.

{ 
background-color : #f1ee18 ; /* All recognition */ 
.background-color : #00deff\9 ; / * IE6, 7, 8 recognition */ 
+background-color : #a200ff ; /* IE6, 7 recognition */ 
_background-color : #1e0bd1 ; /* IE6 recognizes */ 
}

  4. Set a smaller height label (generally less than 10px), in IE6, IE7, the height exceeds the height set by yourself. Hack: Set overflow:hidden for labels that exceed the height; or set the line-height line-height less than the height you set.

  5. Under IE, you can use the method of obtaining general attributes to obtain custom attributes, or you can use getAttribute() to obtain custom attributes; under Firefox, you can only use getAttribute() to obtain custom attributes. Solution: Get custom attributes uniformly through getAttribute().

  6. Under the Chrome Chinese interface, the text smaller than 12px will be forced to be displayed according to 12px by default, which can be solved by adding the CSS property -webkit-text-size-adjust: none;.

  7. After the hyperlink is accessed, the hover style will not appear, and the hyperlink style that has been clicked and accessed will no longer have hover and active. The solution is to change the order of CSS properties: LVHA ( love hate ): a:link {} a:visited {} a:hover {} a:active {}

14. Why initialize CSS styles

Due to browser compatibility issues, different browsers have different default values ​​for some tags. If CSS is not initialized, there will often be differences in page display between browsers.

15. What is the difference between the calculation method of absolute's containing block and normal flow?

No matter which type it belongs to, you must first find the element whose closest position value is not static among its ancestor elements, and then judge:

  1. If this element is an inline element, the containing block is the smallest rectangle that can contain the padding box (area except margin, border) of the first and last inline box generated by this element;

  2. Otherwise, it consists of the padding box of this ancestor element.

If none are found, it is the initial containing block.

Replenish:

  1. static (default)/relative: Simply put, it is the content box of its parent element (that is, the part where padding is removed)

  2. absolute: Find the closest element positioned absolute/relative upwards

  3. fixed: its containing block is always the root element (html/body)

16. Does the visibility property in CSS have a collapse property value? What's the difference in the future under different browsers?

When an element's visibility property is set to the collapse value, it behaves the same as hidden for normal elements.

  1. In chrome, there is no difference between using the collapse value and using hidden.

  2. firefox, opera and IE, there is no difference between using the collapse value and using display: none.

17. What is the difference between display:none and visibility:hidden?

display:none does not display the corresponding element and no longer allocates space in the document layout (reflow + redraw)
visibility:hidden hides the corresponding element and retains the original space in the document layout (redraw)

18. What will happen when position and display, overflow, and float are superimposed on each other?

The display property specifies the type of box that the element should generate; the position property specifies the positioning type of the element; the float property is a layout method that defines in which direction the element floats.
Similar to the priority mechanism: position: absolute/fixed has the highest priority. When they are present, float does not work, and the display value needs to be adjusted. Elements positioned by float or absolute can only be block elements or tables.

19. What is your understanding of the BFC specification (block formatting context: block formatting context)?

The BFC specifies how the internal Block Box is laid out.
Positioning scheme:

  1. The inner Boxes are placed one after the other in the vertical direction.

  2. The vertical distance of the Box is determined by the margin, and the margins of two adjacent Boxes belonging to the same BFC will overlap.

  3. The left side of each element's margin box touches the left side of the containing block's border box.

  4. The area of ​​the BFC will not overlap the float box.

  5. BFC is an isolated and independent container on the page, and the child elements inside the container will not affect the elements outside.

  6. When calculating the height of the BFC, floating elements also participate in the calculation.

BFC can be triggered when one of the following conditions is met

  1. root element, i.e. html

  2. The value of float is not none (default)

  3. The value of overflow is not visible (default)

  4. The value of display is inline-block, table-cell, table-caption

  5. The value of position is absolute or fixed

20. Why do floats appear and when do they need to be cleared? The way to clear the float?

A floating element touches its containing border or the border of a floating element stays. Since the floating element is not in the document flow, the block box of the document flow behaves as if the floating box does not exist. Floating elements float over block boxes in the document flow.
Problems with floats:

  1. The height of the parent element cannot be stretched, affecting elements at the same level as the parent element

  2. Non-floated elements (inline elements) at the same level as the floated element follow

  3. If the first element is not floating, the elements before this element also need to be floated, otherwise it will affect the structure of the page display.

The way to clear the float:

  1. The parent div defines the height

  2. Add an empty div tag after the last floated element and add the style clear:both.

  3. Parent tags containing floated elements add style overflow to hidden or auto.

  4. The parent div defines zoom

21. The problem of overlapping upper and lower margins

Wrap a container around the overlapping element and trigger the container to generate a BFC.
example:

<div class="aside"></div>
<div class="text">
    <div class="main"></div>
</div>
<!--下面是css代码-->
 .aside {
            margin-bottom: 100px;  
            width: 100px;
            height: 150px;
            background: #f66;
        }
        .main {
            margin-top: 100px;
            height: 200px;
            background: #fcc;
        }
         .text{
            /* There is a div outside the box main. By changing the properties of this div, the two boxes belong to two different BFCs, so as to prevent the margins from overlapping*/
            overflow: hidden; //The BFC property has been triggered at this time.
        }

22. After setting the element to float, what is the display value of the element?

Automatically becomes display:block

23. Have you used media queries for the layout of the mobile terminal?

Through media queries, you can define different CSS for different sizes and sizes of media to adapt to the display of the corresponding device.

  1. <head>里边<link rel=”stylesheet” type=”text/css” href=”xxx.css” media=”only screen and (max-device-width:480px)”>

  2. CSS : @media only screen and (max-device-width:480px) {/css样式/}

24. Do you use CSS preprocessor?
Less sass

25. What are the ways to optimize CSS and improve performance?

  1. avoid excessive constraints

  2. Avoid descendant selectors

  3. Avoid chained selectors

  4. Use compact syntax

  5. Avoid unnecessary namespaces

  6. avoid unnecessary repetition

  7. It is better to use names that represent semantics. A good class name should describe what it is rather than what it looks like

  8. avoid! important, other selectors can be selected

  9. Minimize rules as much as possible, you can combine duplicate rules in different classes

26. How do browsers parse CSS selectors?

CSS selectors are parsed from right to left. If you match from left to right and find that it does not conform to the rules, you need to backtrack, which will lose a lot of performance. If matching from right to left, first find all the rightmost nodes, and for each node, look up its parent node until the root element or the matching rule that satisfies the condition is found, then the traversal of this branch is ended. The performance of the two matching rules is very different, because the right-to-left matching filters out a large number of rightmost nodes (leaf nodes) that do not meet the conditions in the first step, while the performance of the left-to-right matching rules All wasted on failed lookups.
After the CSS parsing is completed, the parsing result needs to be analyzed together with the content of the DOM Tree to establish a Render Tree, which is finally used for drawing. When creating a Render Tree (the "Attachment" process in WebKit), the browser determines what kind of Render Tree to generate for each element in the DOM Tree according to the CSS parsing result (Style Rules).

27. Should odd-numbered or even-numbered fonts be used in web pages? why?

Use even-numbered fonts. Even numbers are relatively easier to scale with the rest of the web design. The dot matrix Arial (Zhongyi Arial) that comes with Windows only provides dot matrix of 12, 14, and 16 px from Vista, while 13, 15, and 17 px use a smaller dot. (That is, the space occupied by each word is 1 px larger, but the dot matrix has not changed), so it is slightly sparse.

28. What scenarios are margin and padding suitable for?

When to use margin:

  1. Need to add whitespace outside the border

  2. Blank space does not need background color

  3. When the space between two boxes connected up and down needs to cancel each other.

When to use padding:

  1. Need to add whitespace inside the border

  2. Blank space requires background color

  3. The blank of two boxes connected up and down, hopefully the sum of the two.

Compatibility issue: In IE5 and IE6, when specifying a margin for a float box, the left margin may become twice as wide. Solved by changing the padding or specifying the display: inline of the box.

29. Is the vertical percentage setting of an element relative to the height of the container?

When setting the width of an element as a percentage, it is calculated relative to the width of the parent container, however, for some properties that represent vertical distance, such as padding-top , padding-bottom , margin-top , margin-bottom , etc. , when setting them as a percentage, it is also based on the width of the parent container, not the height.

30. What is the principle of full-screen scrolling? Which properties of CSS are used?

  1. Principle: It is similar to carousel. The overall elements are arranged all the time. Assuming that there are 5 full-screen pages that need to be displayed, the height is 500%, and only 100% is displayed. The rest can be positioned on the y-axis through transform, or through margin-top implementation

  2. overflow:hidden;transition:all 1000ms ease;

31. What is responsive design? What are the basic principles of responsive design? How to be compatible with lower versions of IE?

Responsive web design is a website that is compatible with multiple terminals, rather than making a specific version for each terminal.
The basic principle is to detect different device screen sizes through media queries for processing.
The header of the page must have the viewport declared by the meta.

<meta name="’viewport’" content="”width=device-width," initial-scale="1." maximum-scale="1,user-scalable=no”"/>

32. Parallax scrolling effect?

Parallax Scrolling creates stunning 3D effects by controlling the background to move slower than the foreground as the web page scrolls down.

  1. Advantages of CSS3 implementation
    : short development time, better performance and development efficiency, but the disadvantage is that it cannot be compatible with lower versions of browsers

  2. jQuery realizes the scrolling effect
    by controlling the scrolling speed of different layers, calculating the time of each layer, and controlling the scrolling effect.
    Advantages: Compatible with various versions, and the effect is controllable
    Disadvantages: It requires high requirements for producers

  3. Plug-in implementation
    such as: parallax-scrolling, the compatibility is very good

33. What is the difference between double colon and single colon in ::before and :after? Explain the role of these two pseudo-elements

  1. Single colons (:) are used for CSS3 pseudo-classes, and double colons (::) are used for CSS3 pseudo-elements.

  2. ::before is a pseudo-element defined before the main content of the element with the existence of a child element. Does not exist in the dom, only exists in the page.

The two pseudo-elements :before and :after are new in CSS2.1. Initially, pseudo-elements were prefixed with a single-colon syntax, but with the evolution of the Web, in the CSS3 specification, the pseudo-element syntax was modified to use double colons, becoming ::before ::after

34. How do you understand line-height?

Line height refers to the height of a line of text, specifically the baseline distance between two lines of text. The height function in CSS is height and line-height. The height attribute is not defined, and its final performance must be line-height.
Vertical centering of single-line text: Setting the line-height value to a value of the same size as height can achieve vertical centering of single-line text, in fact, the height can also be deleted.
Vertical centering of multi-line text: You need to set the display property to inline-block.

35. How to make Chrome support text smaller than 12px?

p { font-size : 10px ; -webkit-transform : scale(0.8) ;} //0.8 is the scaling ratio

36. How to make the fonts in the page clearer and thinner with CSS?

-webkit-font-smoothing does not work on windows, but works on IOS devices -webkit-font-smoothing: antialiased is the best, grayscale smoothing.

37. How to deal with position: fixed; invalid under android?

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"/>

38. If you need to manually write animations, how long do you think the minimum time interval is and why?
The default frequency of most monitors is 60Hz, that is, 60 refreshes per second, so the theoretical minimum interval is 1/60*1000ms = 16.7ms.

39. What causes the invisible blank space between li and li? What is the solution?

The arrangement of the line boxes will be affected by the middle blanks (carriage return spaces), etc., because spaces are also characters, these blanks will also be applied with styles and occupy space, so there will be gaps, set the character size to 0, there will be no spaces. .
Solution:

  1. You can write all the <li> code in one row

  2. float: left in float li

  3. Use font-size: 0 in ul (not supported by Google); you can use letter-space: -3px

40. When will display:inline-block display the gap?

  1. There will be gaps when there are spaces. Solution: remove spaces

  2. Solve when margin is positive: margin uses negative value

  3. Solve when using font-size: font-size: 0, letter-spacing, word-spacing

41. There is a height adaptive div, there are two divs in it, one is 100px high, and the other is expected to fill the remaining height

Use position: relative for the outer div; use position: absolute for divs that require adaptive height; top: 100px; bottom: 0; left: 0

42. Explain the image formats of png, jpg, and gif, and when to use them. Have you learned about webp?

  1. png is Portable Network Graphics (Portable Network Graphics) is a lossless data compression bitmap file format. The advantages are: high compression ratio and good color. Available in most places.

  2. jpg is a distortion compression method used for photos. It is a destructive compression that does a good job of smoothing changes in tones and colors. Format used to store and transmit photos on the www.

  3. gif is a bitmap file format that reproduces images in true color in 8-bit color. Animation effects can be achieved.

  4. The webp format is an image format launched by Google in 2010. The compression rate is only 2/3 of that of jpg, and the size is 45% smaller than that of png. The disadvantage is that the compression time is longer and the compatibility is not good. Currently, Google and opera support.

43. What is the difference between the style tag written after the body and before the body?

The page loads top-down and of course the styles are loaded first.
Written after the body tag, since the browser parses the HTML document line by line, when the style sheet written at the end (outline or in the style tag) is parsed, the browser will stop the previous rendering, waiting for the style to be loaded and parsed After the table is re-rendered, FOUC may occur under IE on windows (that is, the page flickering problem caused by style failure)

44. The CSS property overflow property defines how the content of the overflow element content area will be handled?

When the parameter is scroll, a scroll bar will appear.
When the parameter is auto, the scroll bar appears when the content of the child element is larger than the parent element.
When the parameter is visible, the overflowed content appears outside the parent element.
When the parameter is hidden, overflow is hidden.

45. Explain CSS Sprites

Include all the pictures involved in a page into a large picture, and then use the combination of CSS background-image, background-repeat, and background-position for background positioning. Using CSS Sprites can greatly reduce the http request of web pages, thereby greatly improving the performance of the page; CSS Sprites can reduce the bytes of pictures.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324940952&siteId=291194637