I met the CSS

  • Cascading Style Sheet CSS is a cascading style sheet whose main purpose is to add a variety of styling and embellishing effects to HTML tags

How an HTML page introduces CSS

  • Line style: The style attribute written directly into the HTML tag
  • Page-level CSS: Add a style tag inside the head tag
< style type = "text/CSS" > < / style >Copy the code
  • External CSS files: Create an external one.cssFor postfix files, add a link tag inside the head tag
    • Link tag in the href attribute of the CSS file address, preferably in the form of a relative address, link loading will not block HTML loading, HTML and CSS are asynchronous loading
    • Note that there is no priority between the link tag introduction and the style tag modification,Whoever writes it first executes it first, the CSS style written later overwrites the previous CSS style. Sometimes the link is written on the top but the link has not been loaded so the later style is run first. This problem may be caused by the network speed rather than the priority of the two
      <link rel="stylesheet" href="">
      Copy the code
  • Import mode introduced (deprecated)Add a style tag inside the head tag and put @import URL () on the first line. The introduction of the CSS file address in the URL, with or without quotes, has several disadvantages that have led to its obsolescence
    • It must be written on the first line, or together on the first line if there are more than one
    • IE6 can only be used up to 31 times in the environment, this number is said to have been tested bit by bit by alibaba’s developers.
    • When the program reads import, it will ignore import and load the CSS file of import after all the contents of HTML, including images, are loaded. That is, the CSS file introduced by import is loaded synchronously with HTML
  • Difference between link and import
    • Link is an XHTML tag that defines other transactions, such as RSS, in addition to loading CSS; @import belongs to CSS and can only load CSS
    • Link references CSS are loaded at page load time; @import requires the page to be loaded after the page is fully loaded
    • Link is an XHTML tag with no compatibility issues. @import was introduced in CSS2.1 and is not supported by older browsers
    • Link supports using JS to control the DOM to change styles; @import is not supported
    • Link has a higher style weight than @import

CSS selectors

  • The CSS selector allows you to find the element you want to style and then style it

  • Id selector This ID is a unique identifier. An element can only have one ID, and an ID can only be given to one element. Then in the CSS file, select the element with the id by #id {}

  • The class selector adds the class attribute to the attribute of the element. The attribute adds a class name to the element. Each element can have multiple class names, and the same class name can be assigned to many elements

  • Tag selectors such as div {} will be selected as long as they are div tags

  • Wildcard selector * {}, all tags are selected and styled, including the body TAB

  • Parent selector (derived selector)

    • For example, div p {}, the weight of p under div is the result of the sum, and the id and class can also use parent-child selectors
    • In the actual development, due to the attention to the energy consumption of the browser when looking for elements, the general parent-child selector does not exceed 4 layers, such as: div P strong EM span, the reading order isThe shorter the path chain, the more efficient it is to read from the right to the left of the selector. Generally, it is best to have no more than four levelsWhy is that?
      • If you look from left to right, every time you find a parent tag, you iterate over all the tags below it to see if there’s a next tag. In the selector example above, the browser finds the div tag, and then iterates through all the children of the div to find the strong tag. It then iterates through all the elements under the strong tag to find em, and so on, which is very performance consuming and very slow
      • To go from right to left, the browser simply finds the SPAN TAB, goes up from the span node, and stops looking as soon as it finds em, and so on. The benefits of not having to traverse all the nodes and having to traverse very few points are obvious, which is very fast and does not cost performance
  • Direct child element selectors such as div > strong

      / / right
      <div>
      <strong></strong>
      </div>
    
      / / error
      <div>
      <em>
      <strong></strong>
      </em>
      </div>
    Copy the code
  • Parallel selectors can be selected using something like div.select {}, which is selected only if both div and.select are applied to the same tag, with the tag name first and the others second

    <div classSelect = "" > < / div >Copy the code
  • Group selectors such as div, p, em, strong {} can be used to select all of these tags and add the same style, with a comma between them

  • Pseudo class selector

    • Use to style existing elements when they are in a state that changes dynamically based on user behavior, such as when the user hovers over the specified element:hover To describe the state of the element
    • Although it is similar to a normal CSS class in that it can style existing elements, it can only style elements in a state that the DOM tree cannot describe, so it is called a pseudo-class
    • Common pseudo-classes
      • :link, sets the CSS style of the a tag before it is accessed
      • :visited, set the CSS style of a tag that has been visited in its linked address
      • :hover, sets the CSS style of the element when it hovers
      • :active, sets the CSS style of the element when it is activated by the user (the event that occurs between mouse click and release)

  • Pseudo element selector
    • Use to create and style elements that are not in the document tree, for example :before to append text to an element and style the text
    • Although the text is visible to the user, it is not actually in the document tree (some pseudo classes or pseudo elements are still in the experimental stage, it is recommended to check browser compatibility on websites like Can I Use before using them, pseudo classes or pseudo elements in the experimental stage will be marked in the title)

  • Property selector

    Attribute selector collocation is more free, can be selected according to the attribute or attribute value, can also be selected according to part of the attribute value, the specific rules are as follows

Note 1, usually do not add id tag, but by adding the class name, because id represents a unique identifier, generally use ID to mark, background PHP will be based on the extracted ID to replace their tag. 2, when writing the class name, we must pay attention to semantic, to meet the semantic standards, to use English words to name, rather than using the unknown ABC class name

The weight and priority of the selector

  • Weight value
    • ! Portant: infinity +1 is still infinite in math, but in CSS selector weight value
    • Inline style: 1000
    • Id: 100
    • Class, attribute, pseudo class: 10
    • Tags, pseudo-elements: 1
    • Wildcard: 0
  • priority
    • The element’s declared style weight is higher than the browser’s default style
    • The browser default style has more weight than the style inherited from the parent element
    • ! Important > Inline > ID selector > Class selector (attribute, pseudo-class) > Tag selector (pseudo-element) > wildcard

The execution efficiency of the selector

  • Selectors’ execution efficiency (from highest to lowest) : Id (# myID) > class (.myclassName) > tag (div, h1, P) > adjacent (h1 + p) > child (ul > Li) > descendant (LI A) > wildcard (*) > attribute (a[rel=”external”]) > pseudo-class (a: hover, Li: nth-child)
  • The performance impact of CSS selectors comes from the time it takes for the browser to match the selectors and document elements, so the principle of optimizing selectors is to avoid using selectors that consume more matching time

unit

  • Absolute units: px, in, pt, cm, mm
    • Px: Pixels, used on screen displays. Traditionally, one pixel corresponds to one point on the screen, but for HIGH-DEFINITION screens there are more. Any modern display is made up of thousands of pixels, so you can use pixels to define length. CSS defines the display mode of raster images such as photos as 1px by default, and a “600×400” resolution photo is “600px” and “400px”, so the image’s pixels are not consistent with the display device pixel (which may be very small), but with the unit px. This allows the image to be completely aligned with the rest of the page
  • Relative units, such as %, EM, REM, VW, vH, vmin, vmax
    • % : The percentage of the child element relative to the value of the parent attribute. If the parent is 100px high, 50% of the child element is 50px
    • Em: there must be a reference value, which is not fixed but has different reference values for different attributes
      • Font-size: 1em = the font size of the parent element. If the parent element has no font size, use the default font size of the browser
      • Other attributes (border, width, height, padding, margin, line-height) : Em is calculated by referring to the font size of the element. 1EM equals the font size set for the element. Similarly, if the element is not set, search up
    • Rem: rem reference is fixed, relative to the root element HTML font size calculation, REM R is root, CSS3 new attribute, some browsers are not compatible, even under the mobile android 4.3 is not compatible, but in the long run this is also necessary
    • vw/vh/vmin/vmax
      • Based on the viewport size (the size of the area the browser uses to display content)
      • Many times in the web need to use full screen or half of the screen size, especially on mobile terminals, screen sizes are various, these four are very suitable
      • Vw: Based on the width of the window, 1vw is equal to 1/100th of the window width
      • Vh: Based on the height of the window, 1Vh is equal to 1/100th of the window height
      • Vmin: Calculated based on the minimum in VW and VH, 1vmin is equal to 1/100th of the minimum
      • Vmin: Calculated based on the minimum in VW and VH, 1vmin is equal to 1/100th of the minimum

Chrome’s minimum font size is 12px, and even if it is set to 10px it will render to 12px

The box model

concept

  • When a document is laid out, the browser’s rendering engine describes each element as a rectangular box, according to one of the standards called the CSS Basic Box Model. The boxes use a model to describe the space they occupy. CSS determines the size, position, and properties of these boxes (e.g. color, backview, border size…).
  • A box consists of four parts: margin, border, padding, and content.
    • Content is not made up of attributes, it’s made up of what we write and the width and height attributes
    • Margin Sets the distance of the element from the outside element or the browser border, which is a compound property: Margin-top, margin-right, margin-bottom, margin-left, or the attribute value of each attribute can be written separately. The compound value can be written in four ways
      • Four values: up, right, down, and left
      • Three values: up, left, right, and down
      • Two values: up, down, left, and right
      • 1 value: the four directions are the same value
    • Padding is also a compound property (reference margin)

Note that the body element has a default margin of 8px, and that the tag also has some margins by default. Because these styles can affect the layout, it is generally necessary to remove these default styles: The *{} wildcard selector is usually used in development to initialize the style, because the wildcard has the lowest priority. If you want to add a style later, any style setting will be higher than the wildcard selector, but if it is not set, the browser will default to the initialization style

Box computing

  • There are two types of CSS box models: the standard W3C box model and the Weird (IE) box model
  • The standard W3C box model model
    • According to W3C standard, the width value of an element is the width value of the content in the box model, and the height value is the height value of the content in the box model. Therefore, under the standard box model:
      Width = width(content width) + margin-left + border-left + padding-left + Padding-right + border-right + margin-right Actual box placeholder height = height(content height) + margin-top + border-top + margin-top + padding-bottom + border-bottom + margin-bottomCopy the code

  • Weird box model
    • Border-left + padding-left + content + padding-right + border-right; border-left + content + padding-right Height in the same way
      Width = border-left + padding-left + content width + padding-right + border-right height = border-left + padding-left + Content width + padding-right + border-right box actual space width = margin-left + Content + margin-right box actual space height = margin-top + content + margin-topCopy the code

How the box model is transformed

  • Modern browsers use the W3C’s standard box model by default, but if you need a weird box model, you can use box-sizing, which the W3C added to CSS3
box-sizing: content-box // Standard box model, default
box-sizing: border-box // Weird box model
Copy the code

Note: 1, only the firefox browser support padding – box attribute value 2, IE browser in getComputedStyle width/height is calculated according to the standard model, regardless of the box – value of sizing

Formatting context

  • By default, boxes are arranged one after another from left to right, top-down, according to the sequence of elements in the HTML
  • Different boxes are arranged using different formatting contexts. Each formatting context has a different set of rendering rules that determine how its children will be determined and how they will relate to and interact with other elements

BFC

  • Block Format Context
  • Definition of BFC in W3C specification
    • Floating elements, absolutely positioned elements, block-level containers that are not block-level boxes (such as inline-block, table-cells, table-captions), block-level boxes that do not have unavailable overflow value, Both create new BFC (block-level format Context) for their content
    • In the BFC, boxes are arranged vertically one after the other from the top. The vertical gap between two boxes is determined by their margins. The vertical margins of two adjacent block-level boxes will merge
    • Margin-left of each box in the BFC touches the left edge of the container, border-left, and vice versa
  • MDN defines BFC as: Block Formatting Context (BFC) is a part of the visual CSS rendering of Web pages. It is the area where block-level boxes are generated during layout and the area where floating elements interact with other elements
  • In short, a BFC is a separate rendering area that isolates elements inside the BFC from elements outside the BFC. The layout of all elements inside the BFC does not affect the layout of elements outside the BFC. It determines how its children will be positioned and how they will relate and interact with other elements. This render area only applies to block-level elements. Okay
  • BFC rendering rules
    • Block-level boxes are placed vertically, one on top of the other, with each box occupying the entire container horizontally
    • The vertical distance of block-level boxes is determined by the upper and lower margins. The margins connected by two or more block-level boxes in the same BFC will overlap. If they are both positive, the maximum value will be taken; if they are both positive and negative, the sum value will be taken; if they are both negative, the one with the largest absolute value will be taken
    • The float element is also involved in calculating the height of the BFC
  • Trigger landing
    • The root element (HTML element) or the element containing the root element
    • Float element (float property is not None)
    • Absolute position element (position is absolute or fixed)
    • Overflow values are not visible block elements (hidden, auto, Scroll)
    • Inline block element (element display is inline-block)
    • Table cell (element display is table-cell, HTML table cell default value)
    • Table title (display element as table-caption, HTML table title default to this value)
    • Elastic box element (display as flex or inline-flex)
    • Grid elements (display grid or inline-grid)
    • The element whose display value is flow-root
    • Contain elements whose contain value is Layout, Content, or strict

Block formatting context

  • Landing the role of
    • Margin-bottom and margin-top are 10px, and the distance between the two divs is not 20px, but only 10px!

      <div class= "top" > top < / div ><div class="Bottom">bottom</div>
      Copy the code

      Add a parent layer to each div, and then add overflow:hidden to each div; Margin merging can be solved by triggering BFC via parent div

      <div class= "wrapper" ><div class="Top">top</div>
      </div>
      <div class="Wrapper">
          <div class="Bottom">bottom</div>
      </div>
      Copy the code
    • This bug occurs when margin-top is set to the two divs of a structure like the one in the example

      <div class= "wrapper" ><div class="Content"></div>
      </div>
      .wrapper {
         width: 100px;
         height: 100px;
         margin-top: 100px;
         margin-left: 100px;
         background-color:yellow;
      }
      .content {
         width: 50px;
         height: 50px;
         margin-top: 50px;
         margin-left: 50px;
         background-color: red;
      }
      Copy the code

      I want a parent div of size 100100 with a child div of size 5050 in the bottom right corner of the parent div and 100px away from the browser border



      The result is that the child div’s margin-top effect is not 50px away from the parent div, but 50px away from the browser border. Since the parent div has a margin-top value, The result is that the effect of the child’s margin-top is not visible. If you change the value of the child’s margin-top to 200px, the child div not only has no distance from the parent div, but also drives the parent div to move down together.This is margin collapse

      Solution: 1, use border to trigger BFC effect: margin collapse problem is very easy to think of the child div does not move relative to the parent because you can not see the parent of the border, can only see the browser border, add a child to the parent can see the border is not the problem solved? So add a property to parent div. Wrapper: border-top: 1px solid red; Sure enough, content and Wrapper are unbound, and the child div can see the parent’s boundaries, but this will change the style of the parent div and not meet the development requirements. 2. Use overflow to trigger BFC effects: Now add a property inside parent div. Wrapper: overflow: hidden; This property means that the child div and parent div are unbound and can move normally without changing their appearance. This method is generally adopted to solve the problem of margin collapse.

      Note: although this approach can be adopted, it is not without drawbacks. Once you change the location of the child div with JS code, there is a risk that part of the child content will be hidden due to overflow

    • Two column layout to prevent text surround code as follows

      <div class='div1'></div>
      <div class='div2'></div>
      .div1 {
          float:left;
          height:400px;
          width:200px;
          border:2px solid red;
      }
      .div2 {
        height:400px;
        border:5px solid green;
      }
      Copy the code

      Trigger landing

      .div1 {
          float:left;
          height:400px;
          width:200px;
          border:2px solid red;
      }
      .div2 {
          height:400px;
          border:5px solid green;
          display:flex;
      }
      Copy the code

  • Landing and hasLayout
    • *zomm: 1This is IEhack because IE6-7 does not support THE W3C BFC and instead uses the private hasLayout property.
    • HasLayout is similar to BFC in terms of performance, but hasLayout itself has a number of problems, resulting in a number of bugs in IE6-7
    • The conditions for triggering hasLayout are similar to those for triggering BFC, and it is recommended to set IE specific CSS properties for elementszoom: 1Trigger hasLayout
    • Zoom is used to set or retrieve the scale of an element, and the value is"1"Even with the actual size of the element, it’s relatively convenient to use Zoom: 1 to trigger hasLayout without affecting the element in any other way
    • Since hasLayout has similar functionality to BFC, it is necessary to trigger hasLayout for the elements that need to trigger BFC. In this way, some special properties of BFC and hasLayout can be generated in modern browsers and IE at the same time. Avoid BFC or hasLayout differences in how an element behaves between browsers
    • In fact, many puzzling problems in actual development are actually caused by this. Of course, if an element doesn’t fire the BFC, try to make sure it doesn’t fire hasLayout

In-depth understanding of BFC

IFC

  • Inline Formatting Context
  • Relative to the block formatting context, boxes are arranged horizontally one after the other, starting at the top of the containing block, which visually aligns content on a line with other inline elements until the line is full and then wraps
  • Horizontal margin, border, and padding are preserved between boxes
  • Boxes can be aligned vertically in different ways: at the top or bottom, or according to the baseline of the text in them
  • Inline boxes are divided into inline boxes and atomic inline-level boxes. The former is generated by non-displacement elements whose display value is inline. The latter is generated by inline replacement elements or elements whose display values are inline-block, inline-table, inline-flex, and inline-grid. Typical substitutable elements are<img>, <object>, <video>, and form elements such as <textarea>, <input>
    • For non-replacement elements, such as a and SPAN, you can set a horizontal margin but not a vertical margin. For border and padding, The vertical direction can be set but is not increased when border-top and padding-top reach the top of the page
    • For replacing elements such as input and img tags, margin, border, and padding can be used normally
  • IFC rendering rules
    • In-line boxes in IFC will be rendered according to the following rules (there are a lot of rules, mainly line boxes, line folding mechanism, horizontal alignment, vertical height and vertical alignment)
    • The boxes are placed horizontally on top of each other, wrapping lines when the container is not wide enough
    • In the horizontal direction, the space occupied by the outer margin, border and inner margin of these boxes will be calculated, but the vertical border, padding and margin of the inner box will not extend the height of the box
    • In the vertical direction, the boxes may be aligned in different ways that can be passedvertical-align The default alignment is baseline
    • Each row will generate a line box containing all the boxes in the row. The width of the line box is determined by the containing block and the existing float
    • The left and right sides of a row box are generally close to its containing block, but this changes with the presence of float elements. The float box is positioned between the edge of the containing block and the edge of the row box, so that the available width of the row box is less than the width of the containing block
    • When the total width of all boxes is less than the width of the row boxes, then the horizontal layout in the row boxes is determined bytext-alignAttribute to determine
    • When an inline box exceeds the width of the inline box, it is divided into multiple boxes, which are distributed among multiple inline boxes. If an inline box cannot be split (for example, it contains a single character, or the word-breaking mechanism is disabled, or the inline box is affected by the white-space property being nowRAP or Pre), then the inline box will overflow the line box
    • When the margins, Borders, and padding are split, the margins will not have any visual effects (or any other split, as long as there are multiple margins).
    • The height of the row box is calculated from the element with the highest actual height in the inner element. The height of each row box may be different because of the different contents
    • In a row box, when the height of the contained inner container is less than the height of the row box, the vertical position of the inner container can be determined by its own vertical-align property

Note: Block-level elements are not allowed in IFC environments. If a block-level element is inserted into an IFC, the IFC will be destroyed into a BFC, and the element or text before the block-level element and the element or text after the block-level element will be automatically surrounded by an anonymous block box

positioning

  • The hierarchical model of elements in CSS is primarily determined by the Position property
  • Position means position, and this property applies position to the element
  • staticThe element is static when the position attribute is not set. The element appears in a normal stream. The top, right, bottom, left, and Z-index attributes are invalid
  • relative: Relative location, relative is relative to its position in the normal document flow
    • When position is changed to “relative”, the positioning of left, top, right and bottom will be shifted relative to their own positions
    • The reference to relative is the element itself
    • ** When an element is set to position:relative without setting the left, right, top, and bottom attributes, the element’s position does not change at all. To move an absolute element relative to an element, set relative ** to that element
  • absolute: Absolute positioning
    • Absolute positioning, which makes an element move out of its original position and then move, makes the element appear spatially layered like an overpass. When an element moves out of its original position, other elements cannot see the element. At the same time absolute can also trigger BFC
    • Absolute The reference to absolute is the nearest positioned parent (except static), and the element is positioned relative to the browser border when each parent is unpositioned
    • When absolute positioning is used, you can use the left, right, top, and bottom attributes to set the distance to the left, right, top, and bottom of the current element, usually in pairs, where left and top are a pair and right and bottom are a pair
  • fixed: Absolute positioning
    • Fixed positioning is relative to the positioning of the viewport, the left and right sides of the web page do not change the position of the advertisement column with the wheel rolling, generally is fixed
  • Sticky positioning is similar to the combination of relative and fixed, and its approximate effect in practical application is “top butt” when the IOS address book scrolls.

    Codepen. IO/xiaomuzhu/p…

z-index

  • The z-index attribute is used to specify the order of positioned elements perpendicular to the direction of the page. There are two attribute values:Auto (default) and integers
    • The z-index attribute applies only to elements of the position element, that is, elements whose position attribute is not static
    • In addition to the default value auto, z-index can be set to any integer, positive, 0, or negative
  • Generally, z-index values are compared according to the following two rules
    • The big one is up here, auto is equal to 0
    • The ones with the same value are listed below in the HTML structure above
  • Z-index Default value auto equals 0,z-index: 0;And the defaultz-index:auto;There is a difference
    • Elements whose z-index is set to an integer value, including 0, create a cascading context of their own. Once a cascading context is created, the cascading order of the child elements is computed relative to the parent element, not compared to the external elements
  • When making a Z-index comparison, pay attention to whether the ancestor element has an independent cascading context. The z-index comparison only makes sense in the same cascading context
  • We can think of the elements on the view as a stack of books, and the human eye is the top view. Setting the position of the Z-index is like setting the position of a book in the stack
    Top: Closest to the observer...3layer2layer1layer0Layer Default layer -1Layer -2Layer -3Layer... Bottom layer: farthest from the observerCopy the code

Cascading context and cascading order

Cascading context

  • Stacking context is a three-dimensional concept in HTML. In the CSS2.1 specification, the position of each box model is three-dimensional: the X, Y, and Z axes representing stacking on a flat canvas. Normally element on the page along the X axis and Y axis tile, was not aware of them on the Z axis cascading relationship, and once the stack elements, then will be able to find an element may be covered another element or covered by another element, HTML elements on the basis of its own attributes take up cascading context space in priority order
  • If an element has a cascading context (that is, it is a cascading context element), it can be interpreted as being “superior” along the Z-axis (the invisible vertical line that represents the user relative to the window or web page facing the screen), which ultimately means that it is closer to the viewer on the screen
  • features
    • A cascading context is layered at a higher level than a normal element
    • A cascading context can block elements from mixing patterns
    • The cascading context can be nested, and the inner cascading context and all its children are subject to the outer cascading context
    • Each cascade context is independent of its sibling, meaning only descendant elements need to be considered when cascading changes or rendering
    • Each cascade context is self-contained, and when an element is cascaded the entire element is considered to be in the cascade order of the parent context
  • How?
    • The root element in HTML itself has a cascading context, called a “root cascading context”
    • The normal element sets position to a non-static value and z-index to a specific value (non-auto), resulting in a cascading context
    • A z – the index values are not for auto flex project (flex item), i.e., the parent element display: flex | inline – flex
    • Any element whose property value is less than 1 (see the Specification for opacity)
    • Elements whose transform property value is not None,
    • Elements whose mix-blending-mode attribute value is not normal
    • Filter Elements whose value is not None
    • Elements whose perspective value is not None
    • The Isolation property is set to the element of the ISOLATE
    • Any CSS properties specified in will-change, even if they are not specified directly, can be found in this article: Using CSS3 will-change to improve page scrolling, animation, and other rendering performance
    • -webkit-overflow-scrolling for the elements set to “touch”

Stacking Level/Level (Stacking Level)

  • The order in which elements are displayed on the Z-axis in the same cascading context, the cascading level of ordinary elements is determined by the cascading context first, so the cascading level comparison is only meaningful in the current cascading context element
  • Among other ordinary elements, it describes and defines the order above and below these ordinary elements on the Z-axis

Cascading order

  • Stacking order means that elements are displayed vertically on the Z-axis in accordance with a specific order rule when they are stacked, so the cascading context and hierarchy mentioned above is a concept, and the cascading order is a rule
  • When elements are stacked without considering CSS3, the following rules are followed for cascading communication, which is notable here
    • Cascading context background/border refers to the background and border of the cascading context element, and each cascading order rule applies to a complete cascading context element
    • The original image does not display the cascading order of inline-blocks. In fact, inline-blocks and inline horizontal elements are at the same level
    • In fact, z-index: 0 and Z-index: Auto can be regarded as the same purely from the level of the cascade. In fact, there are fundamental differences between the two in the field of the cascade context
  • Why are inline elements stacked higher than either floating or block elements?
    • Float and block elements are generally used for layout, while inline elements are generally page content. Content is of course the most important thing in a web page. Therefore, it is important to make the cascading order of content quite high, and important text and image content can be preferentially exposed on the screen when cascading

conclusion

  • The first step is to see if the two elements you are comparing are in the same cascading context
  • If it’s someone with the highest hierarchy, who’s on top
  • If two elements are not in the same cascade context, compare the cascade level of the context they are in
  • When two elements are stacked at the same level and in the same order, the following element is stacked at a higher level than the preceding one in the DOM structure

Cascading Context – Zhang Xinxu

floating

  • The float property allows elements to float in a queue. It lines up elements in a parent row by content and size. When there is not enough space for another element in the row, the elements wrap and float on the next line. When the container is not large enough, the contents will go beyond the scope of the container, but after that, they will still stand in the same formation

  • Floating elements are removed from the document flow like absolute elements, but not from the text flow.

    • Out of the document stream means normal elements can’t see it, and in the text stream means elements whose display attribute is inline or inline-block can still see it, and the text itself is inline
    • The float property automatically changes the display of this element to inline-block, so whatever value you put on display, as long as you have a float property, that element is inline-block, okay
  • The float property has only two values: left, right, and None by default

  • The float property

    • Lay out the elements
    • Like absolute, float elements to create their own unique floating flow
  • Floating flows have two effects

    • Out of the standard document flow but not out of the text flow, it is invisible to normal elements, but it is visible with the text attribute inline or the text itself
    • Internally, the element is converted to an inline-block element
  • Use the float property

    • This is usually used when you don’t know how many children will be in the container, but they are arranged in the same format, set to float for streaming layout

    • Create a newspaper-like overlay of text around an image
  • Floating elements can cause problems

    • The height of the parent element cannot be spread out, affecting elements at the same level as the parent element
    • Non-floating elements of the same class as floating elements follow
    • If the first element does not float, the elements preceding it need to float as well, otherwise the structure of the page will be affected
  • Remove the floating

  • The main purpose of clearing floats is to solve the problem of overlapping elements and parent height collapse caused by floating elements leaving the document flow. These two problems correspond to the two situations that need to clear floats: clearing previous sibling floats and closing child floats (solve parent height collapse).

  • Clears the previous sibling element float

    • Use only on elements that you don’t want to be affected by floating elementsclear: bothCan be
    • Before CSS2, clear worked by automatically increasing the element’s margin-top value so that it ended up below the floating element
    • A clearance has been introduced in CSS2.1: Add extra space above the element margin so that it ends up below the floating element, so if you want to set the distance between the floating element and the clear element, set the margin-bottom of the floating element, not the margin-top of the clear element
  • Closed child element floats

Parent highly collapse problem: when calculating the page layout, if not set the height of the parent element, so the height of the parent element is made up of his child elements highly open, but if the child element is set floating, from the document flow, the parent element to calculate the height will ignore the child elements, even when all child elements are floating will appear the parent element height of 0

  • The solution

    • Add a p (div, etc.) tag at the end of the parent content area, and add a clear float style to the P tag

      1) It is not the parent that clears the floating stream, it is the p tag that separates it. The p tag is wrapped in the wrapper, because the p tag can see the floating element above and the P tag is not floating

      2) Although this method is more intuitive, it is not very elegant because it adds a useless blank label, which is more redundant and inconvenient for later maintenance (it is generally not recommended to use this method).
      <div class= "wrapper" ><div class="Content">1</div>
        <div class="Content">2</div>
        <div class="Content">3</div>
        <div class="Content">4</div>
        <p class="Clear"></p>
      </div>
      .clear {
          clear: both;
      }
      Copy the code
  • Adding pseudo-elements

    • Add an after pseudo-element to the parent element that specifically cleans up floats
      .wrapper::after {
          content: "";
          clear: both;
          display: block; // Can clear float elements, must be block level elements
      }
      Copy the code

      1. A pseudo-element is an element that cannot exist alone. It must be attached to other formal element tags, so it is meaningless to write it alone. After, before: < content > < content > “3, since the pseudo-element is also an element, you can change the display of the pseudo-element to block, so that you can change the style of the wide block level elements

  • Trigger the BFC to clear the float (see the BFC section of this article for trigger methods)

  • Pay attention to

    • IE6 / IE7 does not have pseudo-elements, but hasLayout is unique to IE6 / IE7. Triggering hasLayout is similar to triggering BFC. There are many attributes that can trigger this thing, the most harmless of which arezoomProperty, just write this property IE6 / IE7 can also clear the float
    • But other browsers don’t need the Zoom property, it’s just for IE6 / IE7, so you need a little CSS hack, add a symbol in front of zoom,**zoom: 1; This symbol is recognized only by Internet Explorer 6 / Internet Explorer 7, and is not recognized by other browsers'_'Then only IE6 can recognize it_zoom: 1;
      .wrapper {
          zoom: 1; // Whether the viewport is scaled up or down, 1 remains the same
      }
      Copy the code

CSS3

Introduction to the

CSS3 is an updated version of CSS2. It adds many powerful new features on the basis of CSS2.1. Most of the features of CSS3 are now supported by chrome, Safari, Firefox, Opera, and even 360. CSS3 has also been fully supported since IE10

CSS 3 prefix

  • In writing CSS 3 style different browser may need different prefix, it indicates that the CSS properties or rule has not yet become a part of the W3C standards, is the private property browser, although at present a new version of the browser is don’t need a prefix, but for the sake of better compatible with little prefix or not forward, standards of writing as table order, And then I’m going to add unprefixed
    The prefix The browser
    -webkit chrome/safari
    -moz firefox
    -ms IE
    -o opera

CSS 3 function

  • Provides more powerful and accurate selector, provides a variety of background filling schemes, can achieve gradient color, can change the shape of elements, Angle, can add shadow effects, newspaper layout, elastic box, IE6 hybrid mode box model, new units of measurement, animation effects and more…
  • However, CSS3 compatibility issues are also particularly important. Not all CSS3 attributes have been approved by the W3C standards and require a comprehensive compatibility review manual

Read the CSS3 tutorial for details

extension

What are some ways (CSS) to hide page elements?

  • display: none, itself and all its children are completely hidden, as if they do not exist, occupying neither space nor interaction
  • visibility: hidden, the size of the element remains the same, still occupies space, can be understood as transparent, but not interactive. But if the child element is set to visibility: visible, the child element will still be visible
  • overflow: noneTo hide the overflow portion of the element when the content element overflows the parent container, and use scroll bars to display or directly display the overflow portion, which takes up space and is not interactive
  • z-index: -9999The idea is to put the hierarchy at the bottom so that it is overwritten by other hierarchy elements and appears hidden
  • opacity: 0: Essentially turns the element’s transparency to zero, making it appear hidden but still taking up space and interactive
  • transform: scale(0, 0): Plane transformation, scaling elements to 0, occupying space but not interactive
  • Others use absolute positioning to move elements out of sight or clipping with clip-path

Horizontal spacing problem

  • The display property is set to inline-block during page-writing navigation, which results in a space of about 8px between navigation elements

    <div class="nav">
      <div class="nav-item"><a>navigation</a></div>
      <div class="nav-item"><a>navigation</a></div>
      <div class="nav-item"><a>navigation</a></div>
    </div>
    .nav {
      background: 999;
    }
    .nav-item {
      display: inline-block;
      width: 100px;
      background: #ddd;
    }
    Copy the code
  • The reason for this is that when writing code, input whitespace and newline will generate whitespace, and the browser will not ignore whitespace and will automatically merge multiple consecutive whitespace into one, so the so-called gap is generated

  • The solution

    • Code does not wrap. Since newline whitespace results in newline characters, we can write the list item in the example above as a single line, so that the whitespace disappears and the gap disappears. However, for code readable and maintainable, it is generally not recommended to write in a single line
      <div class="nav">
         <div class="nav-item">navigation</div><div class="nav-item">navigation</div><div class="nav-item">navigation</div>
      </div>
      Copy the code
    • Set the font size

      1, Understand that whitespace is ultimately a character, so you can control the size of the resulting gap by setting the font size property. If font size is set to 0, the text character will not be displayed, and the gap will not be displayed

      < font size > < font size > < font size > < font size > < font size > < font size > < font size > < font size > < font size > < font size >
      .nav {
          background: #999;
          font-size: 0; /* Whitespace is 0 */
      }
      .nav-item {
          display:inline-block;
          width: 100px;
          font-size: 16px; /* Reset font size to 16px*/
          background: #ddd;
      }
      Copy the code
    • I thought this would solve the problem completely, but when I set the parent tag character to 0, Safari still showed an interval blank. Since setting the character size to 0 does not work, we will eliminate the interval and replace the code below with the code above. So far, the test works perfectly. The problem is that the character spacing inside item is also set, and the character spacing needs to be set to default
      .nav { letter-spacing: -5px; }
      .nav-item { letter-spacing: normal; }
      Copy the code

Dot overflow

  • When the text exceeds the specified range, all the following text will become “…” In the form of

  • Single-line text overflow dot, requires three properties to work together

    • overflow: hidden;The realization of text overflow container part hidden, convenient behind the dot function
    • text-overflow: ellipsis;What happens to text overflow? Ellipsis means dot display
    • white-space: nowrap;The default state of the text is newline. When it reaches the wall of the container, it automatically moves to the next line. This property keeps the text on one line, even when it reaches the wall of the container
  • Multi-line text overflow dot

    • Although there are attributes for multi-line text overflow dot function, but compatibility is very poor, except for mobile web (because mobile browser versions are generally higher)
    • PC side of the web page is generally in other ways to achieve, like Baidu is through the calculation of the width and height of the text, and then in the last handwritten “…” To achieve multi-line text overflow dot effect
    • If you want to use attributes to complete the function of multi-line text overflow type, use the following attributes
      • The line-clamp property enables the text to display several lines. – WebKit is a webKit-compatible browser. Currently, there are many browsers that do not support the Line-clamp property, and only later versions of WebKit do
      • Box-orient is also very reluctant, so it exists but few companies use it due to compatibility issues
      • Display: -webkit-box is a CSS3.0 property
      text-overflow: ellipsis;
      overflow: hidden;
      display: -webkit-box;
      -webkit-line-clamp: 3; / / the number of rows
      -webkit-box-orient: vertical;  
      Copy the code

How to make the background image not to display text

  • Sometimes web pages are blocked from loading images and CSS styles. If you don’t set any information for the background image, the user doesn’t know what the blank space is. So to make the image appear with text, you can use the following two methods to achieve this effect

text-indent

  • More traditional way: usetext-indentCooperate withWhite-space: nowrap, Overflow: hidden;Let the text inside the element be indented and hidden when CSS is present. The text will not be indented when CSS cannot be loaded, so it can be displayed

Put the background image inside the padding, forcing the height to be 0

  • Background-image can be placed inside the padding, the height of the element itself is 0, and the padding-top is used to support the content area of the element, so that CSS styles can work with overflow: Hidden When used together, text is hidden and will appear normally without CSS styles
.taobao-head .header .logo-bd {
    display: block;
    margin-left: 22px;
    width: 142px;
    padding-top: 58px;
    height: 0;
    overflow: hidden;
    background: url(xxxx) 0 0 no-repeat;
}
Copy the code

Why is translate sometimes used to change position instead of position?

  • Translate is a value of transform. Changing opacity or opacity of transform does not trigger a browser reflow or repaint, only a composition.
  • Changing absolute positioning triggers relayout, which in turn triggers redrawing and composition
  • Transform lets the browser create a GPU layer for the element, but changing the absolute positioning uses the CPU, so translate is more efficient and reduces the drawing time for smooth animations
  • When translate changes position, the element still occupies its original space. Absolute positioning does not