CSS Cheat Sheet - Basics

Table of contents

1. The basic structure of CSS

2. The source and priority of the style sheet

3. The priority of the selector 

4. Source code order

5. px, em, rem units

6. Viewport relative unit

7. Use calc() to define attribute values

8. Some unitless attributes

9. Custom attributes

10. Use JavaScript to dynamically modify custom attributes

11. overflow attribute

12. The common implementation method of positioning the child element in the center of the parent element

 12-1) Absolute positioning method

12-2) Flex layout

12-3) grid layout

13. Owl picker

14. Center the text

1) Use line-height and text-align

2) use flex

15. FlexBox elastic container layout

16. grid grid layout

17. If there is text overflow, replace it with an ellipsis in advance

1. Ellipsis processing for single-line text:

 2. Ellipsis processing of multi-line text:

3. If it is multi-line text but the height and line height are not well controlled:

18. Using pseudo-elements to draw CSS triangles

19. The input element comes with two styles that you may want to override


1. The basic structure of CSS

        The following is a CSS declaration consisting of a property and a value:

color:black;

        A group of declarations enclosed in braces is called a declaration block. There is a selector before the declaration block. Selectors and declaration blocks together form a ruleset.

        Here is a ruleset:

.my-img{
    width: 100vw;
    height: auto;
}

2. The source and priority of the style sheet

        The default style of the browser is the user agent style sheet; the author style sheet is the style sheet written by our developers. If there are the same declarations, the author style sheet will override the declaration in the user agent style sheet.

        Declarations marked with !important will be regarded as a higher priority source, it is difficult to be overridden, and should be used as little as possible.

color:black !important;

        Inline styles will directly override any style sheets or styles from <style> tags.

3. The priority of the selector 

        id selector > class selector > label selector.

        If the number of id selectors is the highest, the rule set wins;

        If the number of id selectors is the same, the rule set with more class selectors wins;

        If the number of id selectors and class selectors is the same, the rule set with more label selectors wins;

4. Source code order

        If two declarations have the same origin and precedence, appear in a later stylesheet, or are in a stylesheet that was introduced later on the page, that declaration wins.

5. px, em, rem units

        px: pixel, relative length unit, relative to the sub-scale of the display screen;

        em: Relative length unit, which is equivalent to the font size of the text in the current object, and may inherit the font size of the parent element;

        rem: relative to the font size of the Html root element;

You can change the size of elements using rem by changing the font size of the html root element (:root is the html element):

:root{
    font-size: 10px;
}

         The browser's default font size is 16px.

6. Viewport relative unit

        The viewport is the border area of ​​the visible part of the webpage in the browser window (excluding the status bar, toolbar, and address bar).

        vh: 1/100 of the viewport height;

        vw: 1/100 of the viewport width;

        vmax: 1/100 of the largest of the viewport height and width;

        vmin: viewport width, 1/100 of the smallest side of high school;

7. Use calc() to define attribute values

        Four arithmetic operations between different units can be performed:

font-size: calc(10px + 1.2em);

        Note: There must be spaces before and after the + and - symbols;

8. Some unitless attributes

        1)line-height

        2)z-index

        3)font-weight

        4)opacity

        5)flex-grow  && flex-shrink

9. Custom attributes

        Custom attribute rules: There must be two hyphens (--) before the variable name, and the variable name must be declared in a declaration block. When the variable is to be used, the function var (custom variable) is called.

        If a custom attribute is defined in a ruleset belonging to a tag, then its descendants can use the custom attribute. (declared in the :root selector, then the variable is available throughout the page).

:root{
    --my-font-size: 20px;
}

div{
    font-size: var(--my-font-size);
}

10. Use JavaScript to dynamically modify custom attributes

let rootEle = document.documentElement;        // 获取根元素
let styles = getComputedStyle(rootEle);        // getComputedStyle() 获取一个元素的style对象
let myFontSize = styles.getPropertyValue('--my-font-size');
console.log(String(myFontSize).trim());        // 将输出 20px

var size = parseInt(myFontSize);
rootElement.style.setProperty('--my-font-size', size + 2 + 'px');    // 将--my-font-size 设置为22px

11. overflow attribute

        Control the behavior of overflowing content, support four values: auto, scroll, hidden, visible;

        1) auto: the scroll bar is displayed only when the content overflows;

        2) scroll: horizontal and vertical scroll bars may be displayed on some operating systems, even if they do not overflow, the scroll bars will be grayed out at this time;

        3) overflowX, overflowY set the overflow in a single direction, and support the above four values.

12. The common implementation method of positioning the child element in the center of the parent element

    <div class="parent">
        <div class="child"></div>
    </div>

 12-1) Absolute positioning method

.parent{
    position: relative;
}
.child{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
}

12-2) Flex layout

.parent{
    display: flex;
    justify-content: center;
    align-items: center;
}

12-3) grid layout

.parent{
    display: grid;
    justify-content: center;
    align-content: center;
}

13. Owl picker

        Basic form: .className * + *{...}

        Indicates to select non-first elements among all sub-elements under the specified element.

    <div class="outer">
        <div class="inner">
            <ul>
                <li>a</li>
                <li>b</li>
                <li>b</li>
            </ul>
        </div>
        <div class="inner">
            <ul>
                <li>a</li>
                <li>b</li>
                <li>b</li>
            </ul>
        </div>
        <div class="inner">
            <ul>
                <li>a</li>
                <li>b</li>
                <li>b</li>
            </ul>
        </div>
    </div>

        li{
            margin: 6px 0;
        }
        .inner * + *{
            background-color: brown;
        }

        The element under .inner is ul, here all the second to third elements under li will be selected, and the background will be set to red.

 Attachment: Select the first element of all child elements under the specified element

.inner * :first-child{
    background-color: pink;
}

14. Center the text

<div class="text">文字内容</div>

1) Use line-height and text-align

        .text{
            width: 100px;
            height: 50px;
            background-color: antiquewhite;

            text-align: center;
            line-height: 50px;
        }

2) use flex

        .text{
            width: 100px;
            height: 50px;
            background-color: antiquewhite;

            display: flex;
            justify-content: center;
            align-items: center;
        }

15. FlexBox elastic container layout

1. Set display: flex; or display: inline-flex; to set the element as a flexible container, and its direct child elements are flexible child elements.

        Flex child elements are arranged in order from left to right by default.

        A flex container can fill the width like a block element, but flex child elements may not necessarily fill the width of the flex container.

        The height of the flexible child elements is equal (flex-direction:row;, that is, the default direction arrangement), the height is determined by their content.

2. By default, sub-elements are sorted according to the main axis, the direction of the main axis is from left to right, the direction of the sub-axis is perpendicular to the main axis, and the direction is from top to bottom.

3. The auto outer margin of direct sub-elements in the flexible box will automatically fill all the available space, that is, the maximum distance from the outer side.

4、flex

        4-1, flex attribute: control the size of the elastic sub-element in the main axis direction (by default, flex-direction: row; set the width of the flex control element in the elastic sub-element. flex-direction: column;, in the elastic sub-element The flex set in the control is the height of the element).

        4-2. flex is a shorthand attribute, including flex-grow, flex-shrink, and flex-basis.

                4-2-1. flex-grow is a growth factor, and the extra space will be allocated according to the growth factor of each flex sub-container. If a flex-container has a growth factor of 0, then its width (or height) will not exceed its flex-basis value. If a flex container has a non-zero growth factor, it will grow until all remaining space is allocated. The larger the value of flex-grow, the higher its weight. A flex child with a growth factor of 2 is twice the size of a flex child with a growth factor of 1.

                4-2-2. flex-shrink represents the shrinkage weight of each elastic child element when the elastic element overflows. When the content of the elastic element overflows and the flex-shrink of an elastic child element is 0, the element will not shrink; when the flex-shrink is not 0, it will shrink, and the greater the weight, the greater the proportion of shrinkage.

                4-2-3. flex-basis defines the base value of element size, that is, an initial "main size". The initial value is auto. At this time, the browser will check whether the element has a width attribute set. If so, use width as the value of flex-basis; if not, determine it according to the content. If the value of flex-basis is not auto, then the element's width attribute will be ignored.

         4-3. The default value of flex shorthand attribute is 1 1 0%; corresponding to flex-grow, flex-shrink, and flex-basis respectively. When setting flex, if the value of a sub-property is omitted, the shorthand property will give the default value. If the flex shorthand property is not used, then the child property value that is not set will not have a default value.

       4-4. flex-direction can switch the direction of the main and auxiliary axes. There are four values: row, column, row-reverse, column-reverse.

        4-5. When the direction of flex-direction is column or column-reverse, the main axis will rotate. For inner flex-child elements, flex-grow, flex-shrink, and flex-basis scope the height of the element instead of the width.

            The height of the flex container is determined by the flex child elements, which will exactly fill the container. In the flexible box whose main axis is vertical, the flex-grow and flex-shrink of the child elements will not work unless there is an external force to force the height of the box to be changed, that is, it can be a custom height of the flexible box.

5. Properties of the elastic container:

(1) flex-direction : Set the direction of the main axis

(2) flex-wrap : nowrap (initial value) | wrap | wrap-reverse

            Specify whether the flexible child element will be displayed in a row/column in the flex container (wrap the row/column if it cannot fit)

(3) flex-flow : Shorthand for <flex-direction> <flex-wrap>

(4)justify-content:flex-start (初始值) | flex-end | center | space-around | space-between

            Controls the position of the element on the main axis

(5) align-items : flex-start | flex-end | center | stretch | baseline (aligned according to the baseline of the first line of text)

            Controls the position of the element on the secondary axis

(6)align-content:flex-start | flex-end |center | stretch | space-around | space-between

            If flex-wrap is turned on, align-content will control the spacing of the elastic child elements on the secondary axis. If there is no line break, the align-content attribute is ignored.

6. Properties of elastic child elements:

(1)flex-grow

(2)flex-shrink

(3)flex-basis

(4) flex : The flex attribute is the combined abbreviation of flex-basis flex-grow flex-shrink;

(5)align-self:auto | flex-start | flex-end | center | stretch | baseline

            Controls the alignment of child elements on the secondary axis, overriding the value of the align-items attribute on the container. This property is ignored if the child element's margin in the secondary axis direction is 0.

16. grid grid layout

1. Set the property display:grid; set the container as a grid container, and the direct elements in the container are grid elements.

        Containers behave as block-level elements.

        You can also use inline-grid; the element will behave as an inline element, and the width can only contain the content size.

2. grid-template-rows: define the size of each row of the grid;

      grid-template-columns: defines the size of each column of the grid;

      Use a new unit fr, which is a fractional unit, grid-template-columns: 1fr 1fr 1fr; that is, construct three columns of equal width.

      It is not necessary to use fractional units. grid-template-columns: 1fr 300px; set two columns, the width of the second column is 300px, and the first column occupies all the remaining positions. 2fr is twice as wide as 1fr.

      grid-gap: Defines the spacing between grids. grid-gap: 0.5em 1em; define a vertical distance of 0.5em and a horizontal distance of 1em.

3. Four important concepts in the grid: grid line, grid track, grid unit, and grid area.

4. You can use the shorthand function repeat() when defining multiple repeated grid tracks:

        Such as grid-template-columns: repeat (4, auto); that is, four columns with a width of auto are defined.

        In addition, repeat(3,1fr 2fr); defines six tracks, which is equivalent to writing 1fr 2fr 1fr 2fr 1fr 2fr like this.

      It can also be written like this: grid-template-rows: 1fr repeat(2,2fr 4fr) 1fr; it is equivalent to 1fr 2fr 4fr 2fr 4fr 1fr.

5. The default number of grid lines:

    Columns from left to right, 1 2 3 4 5...;

    Row from top to bottom, 1 2 3 4 5...;

You can use the number of the grid line to specify the position of the grid element in         the grid-colum or grid-row attribute : if you want a grid element to span grid 1 to grid 3 in the vertical direction, you can give grid Grid element setting grid-column: 1 / 3; The slash in the middle is only used to distinguish two values, and the spaces before and after are not required.

        Both grid-column and grid-row are shorthand attributes, such as grid-row is shorthand for grid-row-start and grid-row-end.

        Also, the span keyword can be used to specify a grid track length . For example, grid-row: span 2; tells the browser that the element needs to span two grid tracks in the vertical direction (that is, two lines).

6. Name the grid lines:

        You can name the grid lines, and use the grid line names to replace their default numbers during layout.

        For example: grid-template-columns: [start] 1fr [center] 2fr [end]; this declaration defines two grid tracks, 1fr and 2fr respectively, and three grid lines named start, center and end. Then when defining the position of the grid element in the grid, you can use the name to declare, such as grid-column: start / end;

        You can also provide multiple names for a grid line, such as: grid-template-rows: [top-start] 1fr [top-end,bottom-start] 1fr [bottom-end]; in this statement, the horizontal Gridline #2 has two names.

        It should be noted here that naming the grid lines as top-start and top-end defines an area that covers the space between the two grid lines. The -start and -end suffixes are used as keywords to define both The area between, if you set grid-row: top to the grid element; then he will span the area from top-start to top-end.

        Note that when using repeat(3 , [top-start] 1fr 1fr); to generate the grid, the equivalent writing is as follows: [top-start] 1fr 1fr [top-start] 1fr 1fr [top-start] 1fr 1fr ;

7. Name the grid area:

        In the container: the grid-template-areas attribute sets the grid area;

        In the element: the grid-area attribute sets the area to be placed

    <div class="container">
        <div class="header"></div>
        <div class="content"></div>
    </div>
        .container {
            display: grid;
            width: 500px;
            height: 500px;
            grid-template-columns: 1fr 3fr;
            grid-template-rows: 100px 1fr 80px;
            grid-template-areas:
                "header header"
                "sidebar content"
                "footer footer";
        }

        .header {
            grid-area: header;
            background-color: #5fe929;
        }
        .content {
            grid-area: content;
            background-color: #c22121;
        }

        There are multiple strings in grid-template-areas, each string represents a row in the grid area, and spaces are used to separate the columns in the strings.

        Note: Each area must be set as a rectangle, and cannot be set as other special graphics;

        You can use . as a placeholder name, which leaves a grid cell empty

8. Explicit and implicit grids

        Implicit grid tracks default to auto and they expand to accommodate the content of the grid element. Grid-auto-columns and grid-auto-rows can be set to the grid container to define a size for the implicit grid track. Such as grid-auto-rows: 1fr;

        Use the minmax() function to specify a maximum and minimum size, respectively, and the browser will ensure that the size of the track is between these two.

        Use such as: grid-template-rows: repeat ( auto-fill, minmax(200px , 1fr ) ); then set the minimum row height to 200px;

        The auto-fill keyword in the repeat function is a special value. After setting this value, as long as the grid fits, the browser will generate as many tracks as possible, and will not conflict with the specified minmax() size .

        The combination of auto-fill and minmax() will make the grid generate as many tracks as possible in the available space. If the element is not enough to fill all the grid tracks, auto-fill will result in some empty grid tracks. If empty grid tracks are not desired, the auto-fit keyword can be used instead of auto-fill. It will expand the non-empty grid track to fill the available space.

        By default, when an element cannot be accommodated in a certain row, the layout algorithm will automatically move him to the next row, and find a space large enough to accommodate him in the next row. Use grid-auto-flow to control the algorithmic behavior of the layout. Its initial value is row, and the behavior of this value is described earlier. If the value is column, it will place the element first in the grid column, and only when a column is full, it will move to the next row.

        You can also add an additional keyword dense, such as grid-auto-flow: column dense; it tells the algorithm to fill the gaps in the grid tightly, although this will change the order of some elements. With this value, smaller elements will backfill the empty space created by larger elements.

        By default, each grid element expands to fill the entire grid area, but the child elements of a grid element do not fill the grid element. When using the img tag to display an image, img has a special attribute that can control the scaling and stretching of the image: object-fit. The value can be cover, contain, fill, etc. The default value is fill, the entire image will be scaled to fill the img element. Using cover will expand the image so that it fills the box (part of the image will be cropped); using contain will scale the image so that it completely fills the box (causing blank space in the box).

17. If there is text overflow, replace it with an ellipsis in advance

        The main properties used are: text-overflow

        There are five attributes: clip (clip overflowing content); ellipsis (replace with ellipsis); string (replace omitted text with a given string); initial (default value); inherit (inheritance)

        Note that if you need to use ellipsis to handle overflow content, you need to use it in a block-level element, and use it with white-space: nowrap; (for a single line) and text-overflow: hidden;

        If you want to set the overflow of the text to be replaced by an ellipsis, you generally need to set the height, width and line height of the text element. If you want to set the text content to display two lines, and the width of the element is x, generally set the line height of the text to half the element height to prevent wrapping display.

1. Ellipsis processing for single-line text:

<div class="container">
        如果要设置文本的溢出用省略号代替,一般要设置文本元素的高度、宽度以及文本的行高。
        如要设置文本内容显示两行,且该元素的宽度为 x,则一般设置文本的行高为一半的元素高度,防止换行展示。
</div>
        .container {
            background-color: antiquewhite;
            width: 200px;
            height: 50px;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
        }

 2. Ellipsis processing of multi-line text:

        Multi-line text needs to wrap, so no white-space is needed: nowrap;

        Use display:-webkit-box; elastic box layout.

        .container {
            background-color: antiquewhite;
            width: 200px;
            height: 50px;
            text-overflow: ellipsis;
            padding: 0 16px;
            box-sizing: border-box;

            /* white-space: nowrap;    如果是一行以上的就要开启换行 */
            line-height: 25px;          /* 设置行高 */
            overflow: hidden;
            display:-webkit-box;
            -webkit-box-orient: vertical;	/* 设置对齐方式 */
            -webkit-line-clamp: 2;		    /* 第二行文本后面加省略号 */
        }

3. If it is multi-line text but the height and line height are not well controlled:

        .container {
            background-color: antiquewhite;
            width: 200px;
            height: 50px;
            text-overflow: ellipsis;
            padding: 0 16px;
            box-sizing: border-box;

            /* white-space: nowrap;    如果是一行以上的就要开启换行 */
            /* line-height: 25px; 不控制行高 */
            overflow: hidden;
            display: -webkit-box;
            -webkit-box-orient: vertical;	/* 设置对齐方式 */
            -webkit-line-clamp: 2;		    /* 第二行文本后面加省略号 */
        }

18. Using pseudo-elements to draw CSS triangles

        When the element has no content but the size of the border is not zero, it will form the style shown in the figure below. Four triangles form a square, and each triangle corresponds to a side. You can only make one side have a visible color, and set the other sides to be transparent, then you can make a triangle.

        You can do it directly with the element, or you can use the pseudo-class of the element (::after, ::before)

div{
    content:'';	/* 如需正常显示,则需要content */
    border: 30px  solid;
    border-color: transparent  black  transparent transparent;	 /* 将边框右边的三角形填充为黑色,其余的都是透明的边 */
    position:absolute;
    /* 使用定位将元素定位到需要的位置上 */
}

19. The input element comes with two styles that you may want to override

        outline、border-style

Guess you like

Origin blog.csdn.net/hao_13/article/details/131148216