The following content is basic CSS (1)

1. How to solve the problem of hover event failure after a label is clicked?

Change the order of CSS attributes of a tag: (love and hate principle) Link -> visited -> hover -> active

  1. A: Link: unaccessed style
  2. A. visited B. visited C. visited D. visited
  3. A: Hover: the style when the mouse moves up
  4. A: Active: indicates that the mouse is pressed down

The problem that a: Link style is overwritten by a:visited style can be solved. In CSS, if the same element is defined for different conditions, it is appropriate to put the most general conditions at the top and then down, ensuring that the most special conditions are at the bottom (known as style overlay).

This way, when the browser displays the element, it validates the condition step by step, from special to general.

For example:

I want unvisited links to be blue, suspended links to be green, and visited links to be red:

In the first case, the order I defined is a:visited- red, a: hover-green, and a:link: blue. At this time, it will be found that: when the mouse is placed on the unvisited blue link, it will not turn green, but only on the visited red link, the link will turn green.

In the second case, I change the order of CSS definitions to: A: Link, a:visited, and a:hover. In this case, it will turn green regardless of whether the link you mouse over has been visited or not.

This is because a mouseover unvisited link has both a: Link and a: Hover attributes.

  1. In the first case, a:link is closest to it, so it has both a:link in a:link, a:hover in preference to the duplicate definition of a:hover (the hover style is overridden by link).
  2. In the second case, regardless of whether the link has been visited or not, it first checks whether it meets the criteria of A: Hover (i.e. whether there is a mouse over it). If it does, it turns green. If it does not, it continues to look up until it finds the definition of the condition.

* * * * * * * * * * * * * * * * * * * * * * * * * * *

2. Responsive layout

From what we know so far, there are few scenarios where PC and H5 use a single set of responsive code. Most of them are PC, and H5 maintain a separate set of code.

1. Run the CSS3 media query @media query command

@media screen and (max-width:980px ) { body{ background-color: red; }}Copy the code

2. The flex layout

Elastic box layout model is a new layout method proposed in CSS3 specification.

Purpose: To provide a more efficient way to lay out, align, and allocate space among items in containers

Advantages: This layout pattern is supported by major browsers and can be used in Web application development.

3. The Flex layout

Flexible Box Layouts (Flex), called “Flexible layouts”, provide maximum flexibility in the layout of a web page, replacing the usual float layout, and can be set by any container. Note: After setting the Flex layout, the Float layout of the child element is invalidated

3-1 Four Concepts in Flex

  • Container: If you add display:flex; Then the label is a container
  • Item: The direct child of a container is called an item (it must be a direct child)
  • Main axis: The default sorting direction for items is main axis (horizontal alignment by default, a container can have multiple spindles)
  • Cross axis: the axis perpendicular to the main axis is the cross axis

Figure 1

Figure 2

3-2 Attributes of the container

  • Flex-direction — Attribute determinedThe spindleThe direction of the
  • Flex-wrap — What if the property determines whether the item is not to be sortedA newline
  • Flex-flow — flex-direction and flex-wrapshorthandIn the form of
  • justify-content — The level ofalignment
  • align-items — verticalalignment
  • Align-content — DecidedDogan spindleAlignment of

1.Flex-direction (attribute determines spindle direction)

  • Row (default) : The main axis is horizontal and the starting point isThe left side
  • Row-reverse: the main axis is horizontal and the starting point isThe right end
  • Column: the main axis is vertical and the starting point isThe upper
  • Column-reverse: the main axis is in the vertical direction and the starting point isThe bottom

2.Flex-wrap(property determines how to wrap items if they don’t fit)

  • Norwrap (default) : no line breaks
  • Wrap: The first line is at the top
  • Wrap-reverse: newline with the first line at the bottom

3.Flex-flow (properties are short for flex-direction and flex-wrap)

  • flex-flow: flex-direction || flex-wrap;

4. Justify -content(along the axis — usually aligned horizontally)

  • The flex – start; (Default), items are left justified
  • Flex-end: justify items to the right
  • Center: center
  • Space-between: items are aligned at both ends with equal intervals between items
  • Space-around: Equal spacing on both sides of each item

5. Align-items (property determines how items are aligned on the cross axis — usually vertically aligned)

  • Flex-start starts from the top down
  • Flex-end goes from bottom to top
  • The center is clustered in the center of the display
  • When setting stretch, you cannot set height and baseline alignment for child elements.

Note: The height of the current container must be set for this to work

6. Align-content (property determines the alignment of multiple spindles)

  • Stretch (default) : Axis takes up the entire cross axis
  • Flex-start: align with the starting point of the cross axis
  • Flex-end: aligns with the end of the cross axis
  • Center: aligns with the midpoint of the intersecting axis
  • Space-between: aligned with both ends of the intersecting axes, the spacing between axes is equal
  • Space-around: The spacing on both sides of each axis is equal

3-3 Project attributes

Project attributes

  • order
  • flex-grow
  • flex-shrink
  • flex-basis
  • flex
  • align-self

(1) The order property defines the order of items. The smaller the value, the higher the rank, default is 0)

(2) Flex-grow (property defines the scale of the project. Default is 0, that is, if there is free space, it does not scale.)

(3) Flex-shrink (The flex-shrink attribute defines the shrink ratio of the project. The default is 1, that is, the project will shrink if there is not enough space)

(4) Flex-basis property defines the amount of principal axis space that the project occupies before allocating extra space. Based on this property, the browser calculates whether the main axis has extra space. The default value is auto, the original size of the project, or xx px, the project will take up a fixed space.)

(5) flex (the property is short for flex-grow, flex-shrink, and flex-basis. The default value is 0. 1 Auto. The last two attributes are optional)

flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ];

(6) align-self (attribute allows a single item to have a different alignment than other items, overwriting the align-items attribute. Defaults to auto, inheriting the align-items property of the parent element, or equivalent to stretch if there is no parent element.)

align-self: auto | stretch | flex-start | flex-end | center | baseline;

4. Methods to make elements disappear

  • Visibility: Hidden The element is hidden and will not change the page layout, but will not trigger events that the element is already bound to

  • Display: None Hides the element and changes the layout of the page

  • Z-index =-1 hides the elements and does not change the layout of the page, which is understandably buried under other elements

  • Opacity: 0, which is hidden but does not change the page layout, can also be triggered if the element is already bound to events, such as the Click event, which is used to set the opacity of the image to 0 and then add a click event to upload the file

  • position: absolute; Set a large left negative position so that the element is positioned outside the visible area.

  • transform: scale(0); If you set an element to zoom infinitesimally, the element will not be visible and its original position will be preserved.

  • < div hidden=”hidden” > HTML5 attributes, effects and display: None; Same, but this property is used to record the state of an element;

  • height: 0 ; Set the element height to 0 and eliminate the border;

  • filter: blur(0) ; CSS3 attribute, the greater the value in parentheses, the greater the degree of gaussian blur of the image, and the image can be eliminated when it reaches a certain degree

Strange tricks: Hide the transparent area, zoom in and out of height 0

The difference between rGBA and opacity:

  • Rgba () only works on the element itselfColor or background color.There is no effect on the content of the element.
  • Opacity functions on the element’s own color or background color, as well as the opacity of the content inside the element.

5. CSS box model

In CSS, there are two types of box models, using box-sizing toggle:

  1. When set tocontent-boxWhich are subject toStandard box modelWhen setting the width and height,Only contains the content, excluding padding and border;
  2. And set it toborder-boxWhich are subject toIE box modelWhen setting the width and height,Contains content, padding, and border.
  • Standard (W3C) box model: width = content + border + padding + margin

  • Low version IE box model: width = content + border + padding + margin

6. How does the selector parse

The style system starts with the key selector and works from right to left, dropping the rule if there is no match, or moving left until the match is complete. Therefore, when writing styles, try to choose ID or class selectors as the key selectors, and reduce the style hierarchy, reduce consumption.

7. The selector

7-1 Selector classification

  • Id selector (# myID)
  • Class selector (.myClass)
  • Tag selector (div, H1, P)
  • Wildcard selector (*)
  • Adjacent selector (H1 + P)
  • Child selector (UL > LI)
  • Descendant selector (Li A)
  • Attribute selector (a[rel=”external”])
  • Pseudo-class selectors (:link, :visited, :active, :hover, :before, :after)

7-2 Selector priority

Selector category instructions The weight A weight
! important Enforce the use of this style The highest weights Weights of the highest
Inline style style = “” (1.0.0.0) 1000
The id selector #id (0.1.0.0) 100
Class selectors .id (0.0.1.0) 10
Element selector div (0.0.0.1) 1

Wildcard > Inheritance > Browser default

7-3 Pseudo classes added by CSS3

  • :first-child Matches the first child of the parent element E:first-child: selected as long as E is the first child of its parent. It has to satisfy two conditions, one is the first child, and the other is that this child happens to be E. The following 2 readings are false:

    • Myth # 1: E:first-child selects the first child of E.
    • Myth # 2: E:first-child selects the first E element of the parent element of E.
  • :last-child Matches the last child of the parent element

  • :nth-child(n) matches the NTH child of the parent element (n can be a number, a keyword, or a formula)

    • All rows are selected with n
    • If the parameter is n+ I, the following items are selected from the ith line. For example, if n+3 is selected from the third line, the following items are selected
    • If the parameter is -n+ I, the first I elements are selected. For example, -n+6 indicates the first six elements
    • 2n means multiples of 2 rows are selected, even rows are selected
    • 2n+1 indicates that odd rows are selected
    • 3n indicates that every three rows are selected once
    • Odd means odd, even means even
  • :nth-last-child(n) matches the next-to-last sibling element

  • :nth-of-type(n) matches the NTH sibling of the same type

  • : root root element

  • :not(selector)

7-4 How does the selector work

Query from right to left

8. The difference between pseudo-classes and pseudo-elements

Both describe things that are not in the text stream.

  • Where pseudo-classes are usedSingle colonRepresents when an element is in somestateIs added to the elementstyle, such as a tag hover;
  • Pseudo elements withDouble colonFor compatibility with older browsers, it is sometimes used with a single coloncreateNot in the text streamThe elementAnd add styles to it, such as ::before, to add elements before specifying them.

9. BFC

BFC stands for formatting context

9-1 When an element forms a BFC:

  • The layout of its internal elements does not affect the external elements
  • The layout of external elements does not affect internal elements.

9-2 How to form a BFC

  • The root element
  • Float element: float a value other than None
  • Absolute position elements: Position (Absolute, fixed)
  • Display inline-block, table-cells, flex
  • Table element
  • Overflow for visible (hidden, auto, scroll)

9-3 BFC principles /BFC layout rules

  • The child element inside the BFC, inverticalThe direction, the margins will happenoverlap.
  • The BFC is on the pageindependentThe elements on the outside do not affect the elements on the inside and vice versa.
  • The BFC area does not overlap with the adjacent float Box area. (Can be used to remove floating effects).
  • When calculating the height of the BFC,floatingChild elements of.

9-4 Application of BFC

  • Resolving margin overlap
  • When margin overlap occurs between parent and child elements, the solution is to create a BFC for either child or parent elements
  • The BFC region does not overlap with the float region
  • Remove the floating

Positioning 10.

10-1 Basic meanings

  • Relative position, set the position of the element to relativeTheir ownContent box location, stilloccupyThe original locationspace;
  • Absolute position, set the position of the element to absolute with respect toThe first one position Not for the staticThe padding-box position of the ancestor element, elementDon't takeThe original locationspace;
  • Fixed position, set position of the element to fixed, element relative toTop of browser windowPositioning,Don't takeOriginal position space

10-2 horizontal center

General scheme:

  • Inline elements: The parent element is a block-level element, and the parent element is not a block-level element. Set the parent element to a block-level element, and then set the parent element to text-align:center
  • The picture: Set the imageclear:both; display:block; margin:auto;

Detailed scheme:

  • Solution a:

    1. Margin :0 auto;

    2. Display :inline-block; display:inline-block; display:inline-block; Or display:inline converts it to an inline block-level element/inline element and sets the parent element text-align:center

  • Scheme 2: Use location attributes

    1. Child element set absolute positioning, parent element set relative positioning, left: 50%; Margin-left: 50px(half the width of the child element — fixed width), or transform: translateX(-50%)(variable width)

  • Plan 3: Use Flexbox layout (variable width)

    1. Parent element Settingsdisplay: flex; justify-content: center;

10-3 vertically centered

  • Single-line inline elements: SettingsRow height = height of the parent element
  • Multiline inline elements: Parent element Settingsdisplay:table-cell; vertical-align:middle(Line level, block level, picture all kill)
  • Block-level elements:
    1. Scheme 1: Child element set absolute positioning, parent element set relative positioning, child element set: top:50% andMargin-top: half the height of a child element(height fixed), ortransform:translateY(-50%); (Highly variable)
    2. Option 2: Flex layout, set the parent elementdisplay:flex; align-items:center; (Line level, block level, picture all kill)

10-4 Horizontal and vertical center

An element whose height and width are known

  1. Scheme 1: child element set absolute positioning, parent element set relative positioning, child element setleft:0; right:0; top:0; bottom:0; margin:auto
  2. Scheme two: child element set absolute positioning, parent element set relative positioning, child element settop:50%; Margin-top :- half the height of the child element,margin-left:- half the width of the child element

An element of unknown height and width

  1. Scheme 1 :(positioning attributes) child element set absolute positioning, parent element set relative positioning, child element settop:50%; left:50%(top left corner vertically centered),transform:translate(-50%,-50%)(Achieve offset according to their own positioning)
  2. Option 2 :(flex layout) parent element definitiondisplay:flex; justify-content:center; align-items:center;

10-4 floating

Clear float method:

  • Parent box definitionhighly(height);
  • After the last float elementaddA divAn empty tagAnd add stylesclear: both;
  • Containing floating elementsThe parent tagAdd the styleoverflowFor the hidden/to both;
  • Parent div definitionzoom;

The best way:

Clearfix :after{/* False elements are normal browser clear float methods for inline elements */ content: ""; display: block; height: 0; clear:both; visibility: hidden;Copy the code

So, the clear: both; What effect does it have??

  • Clear is a positioning property in the CSS that specifies which side of an element does not allow other elements to float. Clear :both specifies that elements are not allowed to float on either side.
  • The clear property only works on block-level elements, which is what clears display:block in float styles.
  • In additionvisibility: hidden; height: 0; As long as the value of content is empty, it doesn’t matter.

Layout of 11.

11-1 Fixed width on both sides, adaptive in the middle

  1. floatingSet the left float on the left, set the right float on the right, and the middle will automatically adapt.
  2. Absolute positioningSet the left to absolute position, left: 0px. Set the right to absolute position, right: 0px. Set the center to absolute position, left and right to 300px. The width in the middle will be adaptive.
  3. Flexbox layoutSet the left and right containers to display: flex, set the width of both sides, and set flex = 1 in the middle.
  4. Table layoutSet the width of the entire container to 100%, set all three parts to be tables (display:table-cell), and then set the left cell to 300px and the right cell to 300px. The cell in the middle will be adaptive.
  5. Grid layoutSet the container to a grid layout with a width of 100%, set the grid to three columns, and set the width of each column.

12. Margin overlap

Margin overlap rules

  • When two marginAll is positiveWhen, take the maximum of the two;
  • When the marginAre all negativeAnd then, from position 0, it moves negatively;
  • whenThere is a negative, first take out the largest absolute value of negative margin, and then add it to the largest margin of positive margin, that is, take the absolute value of sum

There are four main solutions to margin overlap:

  • The adjacent siblings margin-bottom and margin-top overlap. You can set one of them to BFC;
  • Margin-top overlap of parent and child elements. You can add a border to the parent element – top | padding – top to separate elements, father and son can also be set for landing the parent element;
  • The height of the parent element is auto, and the parent element is margin-bottom overlapping. In the solution of the second case, you can also set height, min-height, max-height to the parent element.
  • No content element itself margin-top overlaps margin-bottom. Can be set to element border | padding | height

13. Draw triangles with CSS

.triangle { width: 0; height: 0; border-width: 100px; border-style: solid; border-color: tomato transparent transparent transparent; //3 side transparent, side opaque}Copy the code

Magic trick – Remember the number of transparent borders: 3 dots and one line (3 dots and one line are opaque)

14. Implement single-line and multi-line text overflow to add ellipsis

  • Single overflow:
p {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
Copy the code
  • Multi-line overflow:
overflow: hidden; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; / / 3 lines of overflowCopy the code

15. Common units

  • Px: absolute units, pages are displayed in exact pixels
  • Em: relative unit. The reference point is the font size of the parent node. If the font size is defined by itself (the default font is 16px), 1em is not a fixed value for the entire page
  • Rem: relative unit, can be interpreted as “root em”, relative to the root node HTML font size to calculate, CSS3 new properties, Chrome/Firefox /IE9+ support
  • Viewpoint width: 1vw = 1% of the viewpoint width
  • Viewpoint height: 1vh = 1% of viewpoint height
  • Vmin: The smaller of VW and VH
  • Vmax: The larger of VW and VH
  • The percentage % :

16. What properties of CSS can be inherited?

  1. The fontSeries of attributes: font, font-family, font-size, font-weight, font-style
  2. The textProperties: color, text-indent, text-align, line-height, word-spacing
  3. The elementvisibility: the visibility
  4. formLayout properties: Caption -side, border-collapse, border-spacing, empty-cells, table-layout
  5. The list ofAttributes: list-style type, list-style-image, list-style-position

What are the new features of CSS3?

  • Selector (E:last-child matches E, the last child of the parent element.) ;
  • Rounded (border-raduis);
  • Multi-column layout;
  • Shadow and reflection;
  • Text-shadow;
  • Text-decoration;
  • Linear gradient;
  • Rotate/scale/skew/translate;
  • Media enquiries (@media);
  • RGBA and Transparency;
  • @ the font – face properties;
  • Multi-background image;
  • Box size;

Bizarre technique: Media query box model, rotate rounded corner to change (gradient) shadow

18. Why should CSS styles be initialized?

Due to compatibility problems of browsers, different browsers have different default values for labels. If the CSS of the browser is not initialized, the same page may be displayed differently in different browsers.

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

  • Multiple CSS can be merged and HTTP requests minimized
  • Margin: 0 margin: 0
  • Put the CSS file at the top of the page (CSS blocks rendering, and the browser will not render any processed content until the CSS file is requested, downloaded, and parsed. If placed below, when the HTML structure is rendered, the CSS will be parsed and rendered again, causing the page to flash.
  • Avoid descendant selectors. Avoid chain selectors that are too long
  • Margin: 8px 6px 7px 5px;
  • Use semantic naming for easy maintenance (optimization)
  • Use as little as possible! Impotrant, you can select other selectors
  • Follow the box model rules

Bizarre techniques: merge abbreviations and shorten chains, semantic adherence to the box model

20. What is the difference between reflux and redraw?

Reflow: when part (or all) of the Render tree needs to be rebuilt due to changes in element size, layout, hiding, etc.

Repaint: When some elements in the Render Tree need to update their properties, such as color changes, which only affect the appearance, style, and layout of the elements.

Note: each page needs to trigger at least one rearrangement + redraw, and rearrangement (reflux) must trigger a redraw.

Conditions that trigger rearrangement (backflow) :

  • Add or remove visible DOM elements
  • The position of the element has changed;
  • The size of the element has changed, such as margin, width and geometry.
  • Content changes, such as image size, font size changes, etc.
  • Page render initialization;
  • The browser window size changes, such as when the resize event occurs.

Strange skill: Reflux is understood as flow, which will naturally cause changes in layout; Repainting can be understood as surface painting, so it is only a change in appearance.

21. Border :none differs from border:0.

The first is the performance difference:

  • {border: 0; }: Set border to 0 pixels and press border even though it is not visible on the pageDefault Value UnderstandingBorder-width /border-colorApply colours to a drawingThat has beenOccupied memory;
  • {border: none; } is understood as border-style:none. boder:0; Than the border: noneBorder-width :0Why border: NoneperformanceThan the border: 0high;

Compatibility differences:

{border:none; } A border of “none” seems to have no effect on IE6/7, the border still exists, and when the border is “0”, all browsers consistently hide the border.

21. What are BFC, IFC, GFC and FFC?

  • Block formatting context(BFC)–block-levelFormatting context;
  • Inline formatting context(IFC)–inlineFormatting context;
  • Grid formatting context(GFC)–Grid layoutFormatting context;
  • Flex formatting context(FFC)–The adaptiveFormatting context

22. The CSS property overflow property defines how content in the overflow element content area is handled.

  • The scroll bar will definitely scroll out.
  • Auto: scroll bar appears when child element content is larger than parent element.
  • Visible: Overflow content appears outside the parent element;
  • Hidden: overflow hidden;

23. What is the difference between style tags written before and after body?

Typically, pages load from the top down. Place the style tag before the body to load the style first. After the body tag, the browser parses the HTML document line by line to the stylesheet written at the end of the document, causing the browser to stop rendering, wait to load, and rerender once the stylesheet has been parsed. In Internet Explorer on Windows, a FOUC symptom (page flashing) may occur.

24. Is the vertical percentage high relative to the container?

In general, percentage units for child elements are based on parent elements. Margin and padding are exceptions. The height of the element is relative to the height of the container, but the margin and padding are relative to the width of the container.

25. ClientHeight, offsetHeight, scrollHeight, offsetTop, scrollTop

  • High page visible area: the document. The body. ClientHeight
  • High page of text in full: document. Body. ScrollHeight
  • High page visible area (including the side) : document. Body. OffsetHeight
  • The page is rolled high: document.body.scrolltop
  • High screen resolution: window.screen.height

Each HTML element has five attributes: clientHeight offsetHeight scrollHeight offsetTop scrollTop. These attributes are related to the height, scroll, and position of the element.

By reading their documentation, the rules are as follows:

The clientHeight and offsetHeight attributes have nothing to do with the element’s scroll or position.

(1) clientHeight:

  • includingpaddingBut does not includeBorder, horizontal scroll bar, marginThe height of the element. for inlineThe property is always0, unit: px, read-only element.

(2) offsetHeight:

  • includingPadding, BORDER, horizontal scroll bar, but not includedmarginThe height of the element. For inline elements this property is always 0, in px, for read-only elements.

Let’s discuss what happens when there is a scrollbar:

If the child element of the element is higher than the child element and overflow=scroll, the element will scroll, then:

(3)scrollHeight:

  • Because the child element is taller than the parent element, the parent element does not want to be as tall as the quilt element and displays the scroll bar as it scrollsThis element is partially hiddenThe scrollHeightincludingCurrently not visibleThe elements of thehighly.
  • The height of the visible part is actually the clientHeight, which is the height of the visible partscrollHeight>=clientHeightConstant was established. It only makes sense to talk about scrollHeight when there is a scrollbar, and scrollHeight==clientHeight is constant when there is no scrollbar. Unit: px, read-only element.

(4)scrollTop:

  • inWhen you have a scroll bar.Scroll downThe distance between theta and theta is thetaThe shaded portion of the top of the elementThe height of the. inNo scrollbarwhenscrollTop==0Constant was established. The unit is px, readable and configurable.

(5)offsetTop:

  • The currentThe element at the topdistanceClosest to the top of the parent elementIt doesn’t matter if there’s a scrollbar. Unit: px, read-only element.

26. How do I create an equilateral square within a parent element of unknown width

1. The use of padding

< HTML >< head> <meta charset=" UTF-8 "/> <title> New TAB </title> </head> <script></script> <body> <div class="content"> <div Class ="son"> </div> </div> </body> <style>. height: 100px; */ } .son { width: 10%; padding-bottom: 10%; /* padding percentage relative to parent element width */ height: 0; border: 1px solid red; } </style> </html>Copy the code

The effect is as follows:

rendering

2.padding-bottom+:after+absolute

< HTML > <head> <meta charset=" UTF-8 "/> <title> New TAB </title> </head> <body> <div class="content"> <div </div> </div> </body> <style>. background: #ccc; } .content:after { content: ''; display: block; padding-bottom: 100%; } .son { position: absolute; width: 100%; height: 100%; } </style> <script></script> </html>Copy the code

The effect is as follows:

27. The CSS animations

attribute meaning
Animation Used to set animation properties, which is a shorthand property containing six properties
Transition The style transitions used to set elements have a similar effect to animation, but the details are quite different
Transform It is used to rotate, scale, move, or tilt an element, and has nothing to do with the animation that sets the style, just as color is used to set the “appearance” of an element.
Translate (move) Translate is just an attribute value of transform, that is, move.