banner
Zein

Zein

x_id

css3

To achieve separation of content and style; adjust the layout of the page, the color and size of elements, add background images and borders, create animation effects, etc., using CSS.

image.png

selector {
    property: value;
}

/* Tag selector: This CSS rule will apply to all h1 elements in the HTML document, making the text color of these h1 elements blue and the font size 24 pixels */
h1 {
    color: blue;
    font-size: 24px;
}

/* Class selector */
/* <div class="block1"> turns red </div> */
.block1 {
    color: red;
}

/* ID selector */
/* <p id="id1"> turns red </p> */
#id1 {
    color: red;
}

/* Universal selector: Clears the margin and padding of all element tags */
* {
   margin: 0;
   padding: 0;
}

/* Attribute selector */
/* Starting from css2 */
[attribute] { property: value; } /* Matches all elements with the attribute */
[attribute="value"] { property: value; } /**/
[attribute^="value"] { property: value; } /* Matches all elements whose attribute value starts with "value" */
[attribute|="value"] { property: value; } /* Matches elements whose attribute value is "value" or starts with "value-" */
/* css3 */
[attribute$="value"] { property: value; } /* Matches all elements whose attribute value ends with "value" */
[attribute*="value"] { property: value; } /* Matches all elements whose attribute value contains the string "value" */
[attribute~="value"] { property: value; } /* Matches elements whose attribute value contains the word "value" */
  1. The selector specifies which elements the CSS rules apply to; selectors include: tag selectors, class selectors, ID selectors, and universal selectors.
  2. property: value;: A set of CSS declarations.

Compound Selector#

Union Selector#

Separate multiple basic selectors with commas.

p, b, i, span { /* Select all <p>, <b>, <i>, <span> elements and set their color to red; */
    color: red;
}

Intersection Selector#

div.class { /* Both a Div tag and a class */
    color: red;
}

Descendant Selector#

The descendant selector selects all descendant elements within a certain element, regardless of the depth of these descendant elements.

p b { /* Selects all <b> elements within <p> elements, no matter how deeply nested <b> is within <p> */
    color: red;
}

Child Selector#

Selects direct child elements of a certain element.

ul > li {
    border: 1px solid red;
}

Adjacent Sibling Selector#

Selects the sibling element immediately following another element.

p + b { /* Selects the first <b> element immediately following a <p> element */
    color: red;
}

General Sibling Selector#

Selects all sibling elements that are located after a certain element.

p ~ b { /* Selects all <b> elements located after a <p> element, not necessarily immediately following, as long as they are at the same level in the DOM tree */
    color: red;
}

Pseudo-class Selector#

Pseudo-class SelectorDescription
Matches the first child element of the parent
Matches the last child element of the parent
(n)Matches the nth child element in the parent; n is an incrementing natural number, can also be a constant or odd, even
(n)Matches the nth child element of the same type in the parent
Matches the first child element of the same type in the parent
Matches the last child element of the same type in the parent
Matches all unvisited links
Matches all visited links
Matches elements when the mouse hovers over them
Matches links that are clicked (e.g., the state when the mouse is held down)
Matches elements that are checked
Matches each disabled element
Matches any

element that has no child elements

Matches each enabled element
Matches elements that have focus
Matches elements with specified value ranges
Matches all elements with invalid values
(language)Matches each

element whose lang attribute value starts with "it"

(selector)Matches each element that is not a

element

(n)Matches the second to last child element of the parent

(n)Matches the second to last child element of the parent

Matches the only

element in the parent

Matches the only child element in the parent

Matches elements that do not have the "required" attribute
Matches elements with values outside the specified range
Matches elements that have the "readonly" attribute
Matches elements that do not have the "readonly" attribute
Matches elements that have the "required" attribute
Matches the root element of the document, in HTML, the root element is always HTML
Matches the currently active #news element (clicking the URL containing that anchor name)
Matches all elements with valid values

Pseudo-element Selector#

Matches parts of an element (such as the first letter, first line of text, etc.)

Pseudo-elementExample DescriptionCSS
::afterInserts content after the element2
::beforeInserts content before the element2
::first-letterMatches the first character of block-level element content1
::first-lineMatches the first line of block-level element content1
::selectionMatches the element selected by the user
::placeholderMatches placeholder text of form controls (like ); used to customize text styles
<p>strick</p>
<input type="text" placeholder="Please enter"/>
p::first-letter {
  font-size: 200%;
}
p::first-line {
  font-weight: bold;
}
input::placeholder {
  color: red;
}
p::selection {
  color: red;
}

p::before {
  content: "I "<!-- can be an image url('./smiley.gif'); -->
}
p::after {
  content: " Strick"
}

CSS Inclusion#

When multiple stylesheets affect the same element, the browser determines which styles to apply based on the cascading priority rules of conflicting styles: !important > inline styles > embedded styles > external linked styles > browser default styles;

Selector priority: the smaller the selected range, the higher the priority.

image.png

Inline Styles#

Set CSS styles in the style attribute within the element tag. Suitable for modifying simple styles; each declaration key-value pair is separated by ;.

<p style="color:red;font-size:50px;">hello world</p>

Embedded Styles#

Create a

<style type="text/css">
  p {
    color: blue;
    font-size: 40px;
  }
</style>
<p>This is a piece of text</p>

External Linked Styles#

<link rel="stylesheet" type="text/css" href="style.css">

style.css:

@charset "utf-8";
p {
    color: green;
    font-size: 30px;
}

Force Set Highest Priority#

color: green !important;

Style Inheritance#

  1. If an element does not set styles related to its parent element, it inherits the styles of the parent element (only applicable to text-, font-, line- prefixed styles and color properties can be inherited, not applicable to layout styles).
  2. Force inheritance of layout styles.
<p style="color:red;">This is <b>HTML5</b></p> <!--<b> element inherits the style of <p> element-->

<p>This is <b>HTML5</b></p>
<style type="text/css">
  p {
    border: 1px solid red;<!-- border is a non-inheritable style -->
  }
  b {
    border: inherit;
  }
</style>

Box Model#

Web page layout process:

  1. Set the styles of each web element box; place them in appropriate positions.
  2. Fill the box with content.

The distance between content and border is the padding; the distance between boxes is the margin.

image.png

Element Box Types#

Block-level Elements#

  1. Block-level elements occupy a whole line;
  2. Height, width, margin, and padding can all be controlled.
  3. The default width is 100% of the container (parent width).
  4. Text elements cannot contain block-level elements; for example,

    ~#

    .

Common blocks:

<h1>~<h6>、<p>、<div>、<ul>、<ol>、<li>

Inline Elements#

  1. Multiple inline elements can be displayed in one line;
  2. Directly setting height and width is ineffective. They can only adapt to the width of the content.
  3. Inline elements can only contain text or other inline elements.
  4. Links cannot contain links; in special cases, links can contain block-level elements, but converting to block-level mode is the safest.

Common inline elements:

<a>、<strong>、<b>、<em>、<i>、<del>、<s>、<ins>、<u>、<span>

Inline-block Elements#

  1. Multiple inline-block elements can be displayed in one line, but there will be a gap between them;
  2. The default width is adaptive to the content width; height, line height, margin, and padding can all be controlled.

Common inline-block elements:

<img />、<input />、<td>

Type Conversion#

span { /* Convert to block element */
  display: block;
}

div { /* Convert to inline element */
  display: inline;
}

div { /* Convert to inline-block element */
  display: inline-block;
}

div { display: none; /* Hide the element and do not occupy space */
}

Set Element Box Size#

PropertyValueDescriptionCSS Version
widthauto, length value or percentageSet the width of the element1
heightauto, length value or percentageSet the height of the element1
min-widthauto, length value or percentageSet the minimum width of the element2
min-heightauto, length value or percentageSet the minimum height of the element2
max-widthauto, length value or percentageSet the maximum width of the element2
max-heightauto, length value or percentageSet the maximum height of the element2
box-sizingcontent-box border-boxDefault value, the width and height of the element only calculate the content size, excluding padding and border; the width and height of the element include padding and border3, initially an experimental feature in various kernels, required browser prefixes, later no longer needed.
resizenone both horizontal verticalDefault value for ordinary elements, does not allow client users to adjust the size of the element; default value for form textarea elements, client users can adjust the width and height of the element; client users can adjust the width of the element; client users can adjust the height of the element.
div {
  background-color: purple;

  width: 200px; height: 200px;
  min-width: 100px;
  min-height: 100px;
  max-width: 300px;
  max-height: 300px;

  resize: both;
  overflow: auto; /* With this, a draggable size graphic appears */

/*  -webkit-box-sizing: border-box;*/  /* Safari and Chrome */
/*  -moz-box-sizing: border-box;  */   /* Firefox */
/*  -ms-box-sizing: border-box;   */   /* IE */
  box-sizing: border-box;         /* Standard */
  padding: 10px; border: 5px solid red;
}

Set Padding#

Set the size of the internal edge padding of the element.

PropertyValueDescriptionCSS Version
padding-toplength value or percentageSet the top padding1
padding-rightlength value or percentageSet the right padding1
padding-bottomlength value or percentageSet the bottom padding1
padding-leftlength value or percentageSet the left padding1
padding1 ~ 4 length values or percentagesShorthand property1
div {
  padding-top: 10px;
  padding-right: 10px;
  padding-bottom: 10px;
  padding-left: 10px;
}

div {
  padding: 10px 10px 10px 10px;
}

div {
  padding: 10px 20px; /* Top and bottom, left and right */
}

div {
  padding: 10px;
}

Set Margin#

Set the size of the external edge padding of the element.

PropertyValueDescriptionCSS Version
margin-top
margin-right
margin-bottom
margin-left
marginlength value percentage auto: margin automatically occupies the browser widthSet the top padding
Set the right padding
Set the bottom padding
Set the left padding
Shorthand property1
div {
  margin-top: 10px;
  margin-right: 10px;
  margin-bottom: 10px;
  margin-left: 10px;
}

div {
  margin: 10px 10px 10px 10px;
}

div {
  margin: 10px 20px;
}

div {
  margin: 10px;
}

/* Center the box */
div {
  margin: 0 auto;
}

/* Center the box horizontally */
div {
  margin-right: auto;
  margin-left: auto;
}

Margin Collapse When Boxes Are Vertically Aligned#

Adjacent boxes arranged vertically; the actual distance is the maximum value of the two boxes' top and bottom margins, rather than the sum of the margins in other situations.

Margin Collapse of Child Elements When Vertically Aligned#

When a child element adds margin-top, it causes both the parent and child elements to move down together.

Solutions: The motivation for adding margin-top to the child element is generally to adjust the vertical alignment of the child element within the parent element. Better methods to adjust this vertical alignment:

  1. Remove the child's margin, set the parent's padding-top.
  2. Set overflow: hidden on the parent.
  3. Set border-top on the parent.

Handle Overflow#

PropertyValueDescriptionCSS Version
overflow-xoverflow valueSet horizontal overflow3
overflow-yoverflow valueSet vertical overflow3
overflowSame values as above:
auto: the browser handles overflow content. If there is overflow content, a scrollbar will be displayed; otherwise, no scrollbar will be displayed.
hidden: if there is overflow content, it will be cut off directly.
scroll: regardless of whether there is overflow, a scrollbar will always appear. However, different platforms and browsers display differently.
visible: default value, regardless of whether there is overflow, the content will be displayed.Shorthand property2
div {
  overflow: auto;
}

Set Element Visibility#

PropertyValue
display
visibilityvisible: default value, the element is visible on the page. hidden: the element is not visible, but occupies space collapse: the element is not visible, hiding table rows and columns; if not a table, it is the same as hidden; may not be supported by Chrome and Opera.
div { visibility: hidden;
}

And the visibility of the box during debugging is achieved by setting borders and background colors.

Set Element Float#

PropertyValueDescription
floatleft right noneFloating element to the left Floating element to the right Disable floating
clearnone left right bothFloating elements can be tightly attached to the left and right edges Floating elements cannot be tightly attached to the left edge Floating elements cannot be tightly attached to the right edge Floating elements cannot be tightly attached to both edges
#a { /* Floating element to the left */
  background: gray;
  float: left;
  clear: none;
}

#c { /* Floating element to the right */
  background: navy;
  float: right;
  clear: both;
}

#c { /* Disable floating */
  background: navy;
  float: none;
}

Set Element Positioning Properties#

Can be understood as setting the positioning properties, the element rises to a position layer for layout.

PropertyvalueDescription
positionstatic absolute relative fixedDefault value, no positioning. Absolute positioning, removed from the document flow, with the top left corner of the window document as the starting point; using top, right, bottom, left to describe relative distances. Relative positioning, using top, right, bottom, left to describe relative distances. Relative to its original position. Fixed positioning, using top, right, bottom, left to describe relative distances.
header { /* Absolute positioning: starting from the top left corner of the window document */
  position: absolute; top: 100px; left: 100px;
}

header { /* Fixed positioning: will scroll with the scrollbar, achieving a relative stationary effect */
  position: fixed; top: 100px; left: 100px;
}

/* Positioning relative to a certain element: does not leave the document flow layer */
body { /* Set the parent element as relative reference, and do not set coordinates */
  position: relative;
}
header { /* If the parent element has set a reference point, the absolute positioning of the child element will be based on it */
  position: absolute; top: 0px; left: 0px;
}

Set Stacking Order#

PropertyvalueDescription
z-indexauto numberDefault layer Set layer, the larger the number, the higher the layer
header {
  z-index: 100;
}

Layout#

Standard Document Layout#

Only use the layout characteristics of the box type itself + type conversion; generally, the overall structure of the webpage is standard flow layout, and multiple child blocks in one line are special layouts.

If the parent box has no height, the child box will stretch the parent box.

Table Layout#

In the early days, tables were used to describe the structure of web pages by setting the block style width table { width: 100% } to always be 100% of the browser window. Then set the width of the child blocks (cells) as a percentage of the parent block to make the page adapt to the window size.

image.png

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Table Layout</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <table border="0">
        <tr>
            <td colspan="2" class="header">Header</td>
        </tr>
        <tr>
            <td class="aside">Aside</td>
            <td class="section">Section</td>
        </tr>
        <tr>
            <td colspan="2" class="footer">Footer</td>
        </tr>
    </table>
</body>
</html>

styles.css:

/* Basic page styles */
body {
    margin: 0;
}

/* Fluid layout table styles */
table {
    margin: 0 auto;
    width: 100%;  /* Set table width to 100% to adapt to window width */
    border-spacing: 0;
}

/* Header styles */
.header {
    height: 120px;
    background-color: #2714d1;
    text-align: center;
    font-size: 24px;
}

/* Sidebar styles */
.aside {
    width: 20%; /* Set width to 20% */
    height: 500px;
    background-color: #2e53d0;
    padding: 10px;
    box-sizing: border-box;
}

/* Main content area styles */
.section {
    width: 80%;  /* Set width to 80% */
    height: 500px;
    background-color: #4eb776;
    padding: 10px;
    box-sizing: border-box;
}

/* Footer styles */
.footer {
    height: 120px;
    background-color: #f2f2f2;
    text-align: center;
    font-size: 18px;
}

Float~~~~ Layout#

  1. After adding the float property to an element, the element floats above the standard layout blocks, which can be understood as layout performed on the float layer; it also means that if the parent box has no height, the child box will no longer stretch the parent box.
  2. The element has inline-block characteristics.
  3. The elements are top-aligned.

Floating is easy to achieve text wrapping around images:

image.png

image.png

image.png

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Float Layout - Fluid Layout</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body class="clearfix">
  <header>header</header>
  <aside>aside</aside>
  <section>section</section>
  <footer>footer</footer>
</body>
</html>

styles.css:

/* Set body width to auto, so that the page width adjusts automatically according to the viewport */
body {
    width: 100%;
    margin: 0;
    color: white;
    background-color: #333;
}

header {
    height: 120px;
    background-color: #444;
    text-align: center;
    padding-top: 40px;
    font-size: 24px;
}

aside {
    width: 20%;
    height: 500px;
    float: left;
    background-color: #555;
    padding: 10px;
    box-sizing: border-box;
}

section {
    width: 80%;
    height: 500px;
    float: left;
    background-color: #666;
    padding: 10px;
    box-sizing: border-box;
}

footer {
    height: 120px;
    clear: both;
    background-color: #444;
    text-align: center;
    padding-top: 40px;
    font-size: 20px;
}

.clearfix::before, /* Add clearfix class to all parent boxes that need to adapt to height */
.clearfix::after {
  content: "";
  display: table;
}
.clearfix::after { /* Add a child box inside the parent box to clear floats, the purpose is to stretch the parent box that has no specified height */
  clear: both;
}

Positioning Layout#

image.png

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Positioning Layout Example</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            height: 100vh;
        }

        .container {
            position: relative;
            height: 100%;
            background-color: #f0f0f0;
        }

        .box {
            position: absolute;
            width: 200px;
            height: 100px;
            background-color: #3498db;
            color: white;
            text-align: center;
            line-height: 100px;
        }

        /* Position the first box: 50px from the top left corner of the container */
        .box1 {
            top: 50px;
            left: 50px;
        }

        /* Position the second box: 50px from the bottom right corner of the container */
        .box2 {
            bottom: 50px;
            right: 50px;
        }

        /* Position the third box: center of the container */
        .box3 {
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
    </style>
</head>
<body>

<div class="container">
    <div class="box box1">Box 1</div>
    <div class="box box2">Box 2</div>
    <div class="box box3">Box 3</div>
</div>

</body>
</html>

Multi-column Layout#

Multi-column layout is useful for scenarios like horizontally scrolling pages (novels).

PropertyvalDescription
column-widthauto: default value, adaptive length value: set column widthDefines the width of each column
column-countauto: default value; indicates just 1 column number: sets the number of columnsDefines the number of columns
columnsIntegrates column-width and column-count properties
column-gapDefines the gap between columns
column-rule column-rule-width column-rule-style column-rule-colorDefines column borders column-rule-width: separately set border width column-rule-style: separately set border style column-rule-color: separately set border color column-rule: shorthand
column-spannone: default value; indicates no spanning all: indicates spanning across columnsSets a large title that spans columns
column-fill
div {
  column-width: 200px;
  column-count: 4;
  column-gap: 100px;
  column-rule: 2px dashed gray;
  column-span: all;
}

div {
  columns: auto 4;
  column-gap: 100px;
  column-rule: 2px dashed gray;
  column-span: all;
}

Flex Layout#

PropertyValueDescription
displayflex: displays the container box model as a block-level flexible box inline-flex: displays the container box model as an inline-level flexible box
flex-directionrow: arranges from left to right row-reverse: arranges from right to left column: arranges from top to bottom column-reverse: arranges from bottom to topThe arrangement direction of child elements, which is the main axis direction setting
flex-wrapnowrap: default value; all displayed in one row or column, will automatically compress wrap: automatically wraps when flexible items cannot fit, without compression wrap-reverse: automatically wraps when flexible items cannot fit, the direction is opposite to wrap
flex-flowShorthand for the above two
justify-contentflex-start: child elements left-aligned, no gaps between elements flex-end: child elements right-aligned, no gaps between elements center: child elements aligned to the center, no gaps between elements space-between: evenly aligned, remaining blank width serves as spacing between child elements, no gaps on both sides space-around: evenly aligned, remaining blank width serves as spacing between child elements, gaps on both sides space-evenly: evenly aligned, remaining blank width serves as spacing between child elements, gaps on both sides, and margins are the same sizeMain axis alignment method (default x-axis)
align-itemsflex-start: top-aligned flex-end: bottom-aligned center: center-aligned baseline: flexible items are based on the baseline to clear extra space stretch: default, stretches child elements to fill the entire vertical space of the parent box, of course, provided that the child elements do not have a height setCross-axis alignment method, effective only when there is one row and the parent box has height
align-contentflex-start: child elements top-aligned, no gaps between elements flex-end: child elements bottom-aligned, no gaps between elements center: child elements aligned to the center, no gaps between elements space-between: evenly aligned, remaining blank width serves as spacing between child elements, no gaps on both sides space-around: evenly aligned, remaining blank width serves as spacing between child elements, gaps on both sides space-evenly: evenly aligned, remaining blank width serves as spacing between child elements, gaps on both sides, and margins are the same sizeCross-axis alignment method for multiple rows
align-selfflex-start: top-aligned flex-end: bottom-aligned center: center-aligned baseline: flexible items are based on the baseline to clear extra space stretch: default, stretches child elements to fill the entire horizontal space of the parent box, of course, provided that the child elements do not have a height setControl layout of individual child boxes
flexintegerThe width ratio of child elements on the main axis; achieves adaptive width control on the main axis
orderControls the order in which flexible items appear
<div class="flex-container">
    <p>First paragraph</p>
    <p>Second paragraph</p>
    <p>Third paragraph</p>
</div>

.flex-container {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  justify-content: space-around;
  /*align-content: ;*/
  align-items: center;
}

/*.flex-container {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-around;
  align-items: center;
  /*align-content: ;*/
}*/

/* Occupying 5 parts, appearing in the order 231 */
p:nth-child(1) { /* Occupies 1 part of the container space */
    flex: 1; /* Main axis width ratio 1:3:1 */
    order: 2;
    align-self: center; /* Center the first child box */
}

p:nth-child(2) {
    flex: 3;
    order: 3;
}

p:nth-child(3) {
    flex: 1;
    order: 1;
}

image.png

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Personal Homepage</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <header class="header">
            <h1>Welcome to My Personal Homepage</h1>
        </header>
        <nav class="navigation">
            <ul>
                <li><a href="#">Home</a></li>
                <li><a href="#">About Me</a></li>
                <li><a href="#">My Projects</a></li>
                <li><a href="#">Contact Me</a></li>
            </ul>
        </nav>
        <section class="main-content">
            <article class="bio">
                <h2>Personal Introduction</h2>
                <p>I am a web developer who loves programming and technological innovation.</p>
            </article>
            <article class="projects">
                <h2>My Projects</h2>
                <ul>
                    <li>Project 1</li>
                    <li>Project 2</li>
                    <li>Project 3</li>
                </ul>
            </article>
            <article class="contact">
                <h2>Contact Information</h2>
                <p>Email: [email protected]</p>
            </article>
        </section>
        <footer class="footer">
            <p>© 2024 My Personal Homepage</p>
        </footer>
    </div>
</body>
</html>

styles.css:

/* Set basic page styles */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

/* Core container, using flexbox layout */
.container {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
}

/* Header */
.header {
    background-color: #4CAF50;
    color: white;
    padding: 20px;
    text-align: center;
}

/* Navigation bar, arranged horizontally, allows wrapping */
.navigation {
    display: flex;
    flex-flow: row wrap; /* Allow wrapping */
    justify-content: center; /* Center alignment */
    background-color: #333;
}

.navigation ul {
    list-style: none;
    display: flex;
    padding: 10px;
}

.navigation li {
    margin: 0 15px;
}

.navigation a {
    color: white;
    text-decoration: none;
}

/* Main content area, using flexbox layout */
.main-content {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between; /* Evenly distribute child elements */
    padding: 20px;
    gap: 20px;
}

/* Personal introduction area */
.bio {
    flex: 1 1 300px; /* Set a flexible box */
    background-color: #f4f4f4;
    padding: 15px;
    border-radius: 8px;
}

.projects {
    flex: 2 1 400px; /* Set a flexible ratio */
    background-color: #f9f9f9;
    padding: 15px;
    border-radius: 8px;
}

.contact {
    flex: 1 1 300px; /* Set a flexible box */
    background-color: #f4f4f4;
    padding: 15px;
    border-radius: 8px;
}

/* Footer */
.footer {
    background-color: #333;
    color: white;
    padding: 10px;
    text-align: center;
}

/* Adjust layout order */
.projects {
    order: -1; /* Make "My Projects" appear before "Personal Introduction" */
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .navigation {
        flex-direction: column;
    }
    .main-content {
        flex-direction: column;
    }
}

Grid Layout#

Inherited Style Properties#

You can specify properties in the parent element box (div); child elements will inherit, so there is no need to write a child element selector. Most elements have default styles, which may need to be cleared first.

PropertyvalueDescriptioncss
colorcolor valueSet the foreground color of the element1
opacity0 ~ 1Set the transparency of the element3
text-alignSet the horizontal alignment of the element in the boxstart and end are new features added in CSS3, but IE and Opera may not support them yet left: left-aligned, default right: right-aligned, center: center-aligned, justify: content justified1,3
// Clear default styles
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

Box Styles#

PropertyvalueDescriptioncss
vertical-aligndistance length value/percentage relative to the baselineVertical alignment of the box
box-shadowhoffset: X-axis offset of the shadow voffset: Y-axis offset of the shadow blur: (optional) blur radius; a length value, the larger the value, the more blurred the box's boundary. Default value 0, clear boundary spread: (optional) spread radius; a length value, positive value represents the shadow extending outward in all directions from the box, negative value represents the shadow shrinking in the opposite direction color: (optional) sets the shadow color, if omitted, the browser will choose a color by itself inset: (optional): default outer shadow, to make it an inner shadow this value is inset multi-value, separated by spacesBox shadow, generally used for interactive response styles, this is difficult to adjust, it is recommended to directly copy Xiaomi, JD3
outline-colorOutline color3
outline-offsetOffset of the outline from the element's border edge3
outline-styleOutline style, consistent with border-style3
outline-widthOutline width3
outlineShorthand3
cursorauto, default, none, context-menu, help, pointer, progress, wait, cell, crosshair, text, vertical-text, alias, copy, move, no-drop, not-allowed, e-resize, n-resize, ne-resize, nw-resize, s-resize, se-resize, sw-resize, w-resize, ew-resize, ns-resize, nesw-resize, nwse-resize, col-resize, row-resize, all-scrollCursor style on the box, try each one on the left1
div span {
  vertical-align: -200px;
  box-shadow: 5px 4px 10px 2px gray; /* Shadow */
  /* box-shadow: 5px 4px 10px 2px gray inset; */ /* Inner shadow */
  outline: 10px double red; /* Add an outline to the box */
  cursor: move;
}

Font Styles#

body { font-size: 50px; } /* Set the font size of the parent element */
@font-face { font-family: abc; src: url('BrushScriptStd.otf'); } /* Server provides abc font file */
body {
  font-style: ;
  font-weight: ;
  font-variant: ;
  font-size: smaller; /* Set relative font size to the parent element */
  font-family: 楷体, 微软雅黑, 宋体; /* Sometimes for compatibility with many browser systems, several backup fonts can be set */
  /* font: italic bold normal smaller 楷体; /* Assign values in the above order */
  color: red;
  opacity: 0.5;
}

Text Styles#

Property NameDescriptionValueCSS Version
text-decorationText strikethroughnone: no strikethrough underline: text underline overline: text overline line-through: strikethrough blink: makes text blink; basically not supported anymore1
text-transformEnglish text casenone: restores the default state of already transformed case capitalize: capitalizes the first letter of English uppercase: converts English to uppercase lowercase: converts English to lowercase1
text-shadowAdds shadow to textDescribed by four values, e.g.: 5px 5px 3px black The first value: horizontal offset; The second value: vertical offset; The third value: shadow blur (optional); The fourth value: shadow color (optional)3
text-alignSets the horizontal alignment of textstart and end are new features added in CSS3, but IE and Opera may not support them yet left: left-aligned, default right: right-aligned, center: center-aligned, justify: content justified1,3
white-spaceWhite space handling methodnormal: default value, white space is compressed, text wraps automatically nowrap: white space is compressed, text does not wrap pre: white space is preserved; wraps when encountering a newline pre-line: white space is compressed; text wraps when full or encounters a newline pre-wrap: white space is preserved; text wraps when full or encounters a newline1
letter-spacingLetter spacingnormal: sets default spacing Length value: e.g.: "number" + "px"1
word-spacingWord spacingnormal: sets default spacing Length value: e.g.: "number" + "px"1
line-heightSets line height (line spacing)normal: sets default spacing Length value: e.g.: "number" + "px" Number: e.g.: 1, 2.3 %: e.g.: 200%1
word-wrapAllows long English words to breaknormal: words do not break break-word: break words3
text-indentText first line indentationnormal: sets default spacing Length value: e.g.: "number" + "px"1
vertical-alignsub: vertically aligns text as a subscript super: vertically aligns text as a superscriptVertical alignment of text
p {
  text-decoration: underline;
  text-transform: uppercase;
  text-shadow: 5px 5px 3px black;
  text-align: center;
  white-space: nowrap;
  letter-spacing: 4px;
  word-spacing: 14px;
  line-height: 200%;
  word-wrap: break-word;
  text-indent: 2rem;
  vertical-align: super;
}

Vertical Centering with Line Height#

Line height = box height.

image.png

<div>Chinese</div>
div {
  height: 40px;
  line-height: 40px;
}

Border Styles#

The border style property border-style must be declared; the other two properties are optional, as they have default values.

PropertyValueDescriptionCSS
border-style border-top-style border-middle-style border-left-style border-right-stylenone dashed dotted double groove inset outset ridge solidNo border Dashed border Dotted border Double border Groove border Border that gives the element content an embedded effect Border that gives the element content a protruding effect Ridge border Solid border
border-width border-top-width border-middle-width border-left-width border-right-widthLength value/percentage thin medium thickSets the border width, optional, as it has default values
border-color border-top-color border-middle-color border-left-color border-right-colorColor valueSets the border color, optional, as it has default values
border-radius border-top-left-radius border-top-right-radius border-middle-left-radius border-middle-right-radiusLength value or percentageSets the border radius of the four corners, used to create rounded corners; border-radius=50% creates a pure circular control Top left corner Top right corner Bottom left corner Bottom right corner3
border-image-sourceIntroduces background image address3
border-image-sliceCuts the introduced background image3
border-image-widthBorder image width, can set four values for top, right, bottom, left, two values for top and bottom/right and left3
border-image-outsetBorder background expands outward3
border-image-repeatstretch: stretches to fill. Default value repeat: tiles the fill; when the image touches the edge, it is truncated if it exceeds round: tiles the fill; dynamically adjusts the image size according to the border size until it fills the border space space: tiles the fill; dynamically adjusts the image spacing according to the border size until it fills the border spaceArrangement method of border background image3
border-imageShorthand for the above five properties3
div { /* Just set the specific side with a prefix */
  border-width: 2px;
  border-style: solid;
  border-color: red;

  border-radius: 10px 20px 30px 40px;

  border-image-source: url(border.png);
  border-image-slice: 27; /* Just right for 4 images */
  /* border-image-slice: 0 fill; */
  border-image-width: 81px;
  border-image-outset: 20px;
  border-image-repeat: round;
}

div {
  border: 2px solid red;
  border-radius: 10px;
  /* border-top: */
  /* border-middle: */
  /* border-left: */
  /* border-right: */
  border-image: url(border.png) 27/27px round;
}

Background Styles#

PropertyValueDescriptionCSS Version
background-colorColor transparentSets the background color to the specified color Default value, sets the background color to transparent1
background-imagenone urlBatch sets block backgrounds, and if one does not need a background, can separately set none to cancel the background Set background image through URL1/3
background-repeatrepeat-x repeat-y repeat no-repeatTiles the image horizontally Tiles the image vertically Tiles the image both horizontally and vertically Displays only one background image, does not tile1/3
background-attachmentscroll fixedDefault value, the background is fixed on the element, will not scroll with the content The background is fixed in the viewport, the content scrolls while the background does not move, can be used for watermark effects1/3
background-positionLength value/percentage top left right bottom centerOffsets the position of the image using length values Positions the background image at the top of the element3
background-sizeLength value/percentage auto cover containCSS length value, such as px, em Default value, the image displays at its original size Scales the image proportionally so that it at least covers the container, but may exceed the container Scales the image proportionally so that the larger of the width or height aligns with the container horizontally or vertically3
background-originborder-box padding-box content-boxDraws the background inside the element box Draws the background inside the padding box Draws the background inside the content box3
background-clipborder-box padding-box content-boxClips the background inside the element box Clips the background inside the padding box Clips the background inside the content box3
backgroundShorthand for background image1
div {
  background-color: silver;
  background-image: url(loading.gif);
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-position: top left; /* 20px 20px; */
  background-size: auto;
  background-origin: content-box;
  background-clip: padding-box;
}

div {
  width: 400px;
  height: 300px;
  border: 10px dashed red;
  padding: 50px;
  background: silver url(img.png) no-repeat scroll left top/100% border-box content-box;
}

Table Styles#

PropertyValueDescriptionVersion
border-collapseseparate: default value, cell borders are independent collapse: adjacent cell borders are merged2
border-spacinglength valueThe spacing between adjacent cell borders; effective when border-collapse: separate. Independent borders are the premise for setting spacing2
caption-sidetop: default value, the title is above bottom: the title is belowPosition of the table title2
empty-cellsshow: default value, shows borders hide: does not show bordersWhether to show borders for empty cells2
table-layoutauto: default value, stretches the entire cell when content is too long fixed: does not stretch the entire cell when content is too longSpecifies the layout style of the table2
vertical-alignbaseline: content object aligns with the baseline top: middle: bottom:In ,
cells can achieve horizontal alignment using the html text label's text-align property; vertical alignment can be achieved using the CSS style property vertical-align1
table {
  border-collapse: separate;
  border-spacing: 10px;
  caption-side: top;
  empty-cells: hide;
  table-layout: fixed;
  vertical-align: bottom;
}

List Styles#

PropertyValueDescriptionCSS Version
list-style-typenone: no marker disc: solid circle circle: hollow circle square: solid square decimal: Arabic numbers lower-roman: lowercase Roman numerals upper-roman: uppercase Roman numerals lower-alpha: lowercase letters upper-alpha: uppercase lettersList item prefix style1/2
list-style-positionoutside: default value, marker is outside the content box inside: marker is inside the content boxRelative position of the arrangement1
list-style-imagenone: do not use image url: use image via urlImage as list prefix1
list-styleshorthand propertyShorthand for the list1
ul {
  list-style-type: square;
  list-style-position: inside;
  /* list-style-image: url(bullet.png); */
}

ul {
  list-style: lower-alpha inside url(bullet.png);
}

Transformation Effects#

Can be used to create interactive animations for elements, such as a transformation feedback when the mouse hovers over.

2D Transformations#

Property ValuevalueDescription
transformtranslate(x,y): translate, where y can be omitted, indicating no vertical displacement translateX(x): horizontal translation of the element x translateY(y): vertical translation of the element y rotate(angle): clockwise rotation by angle degrees scale(x,y): horizontal scaling of the element by x, vertical scaling by y, y can be omitted to indicate the same scaling ratio for both x and y scaleX(x): horizontal scaling of the element by x scaleY(y): vertical scaling of the element by y skew(angleX angleY): skew the element along the x-axis by angleX degrees, and along the y-axis by angleY degrees, angleY can be omitted to indicate no skew along the y-axis skewX(angleX): skew the element along the x-axis by angleX degrees skewY(angleY): skew the element along the y-axis by angleY degrees matrix(a,b,c,d,e,f): 2D transformation shorthand**x and y values can be length units or percentages; **angle units are usually deg, 1 deg = 1 degree x and y values are numbers, default value is 1; greater than 1, enlarge; less than 1, shrink
div {
  transform: translate(20px,30px); /* Set horizontal and vertical offset of the element */
}

div {
  transform: rotate(45deg); /* Set the element to rotate 45 degrees clockwise */
}

div {
  transform: scale(2,1); /* Set the horizontal scaling ratio of the element to 2, vertical scaling ratio to 1 */
}

div {
  transform: skewX(30deg); /* Set the element to skew along the x-axis */
}

div {
  transform: matrix(a,b,c,d,e,f);
}

3D Transformations#

PropertyProperty ValueDescription
transformtranslate3d(x,y,z): 3D way to translate the element, setting x, y, and z axes translateZ(z): setting 3D way to translate the element along the z-axis scale3d(x,y,z): 3D way to scale an element scaleZ(z): setting 3D way to scale the element along the z-axis rotate3d(x,y,z,a): 3D rotation, a indicates angle, xyz is a number between 0 and 1 rotateX(a): sets the rotation of the element along the x-axis in 3D rotateY(a): rotateZ(a): perspective(length value): sets a perspective projection matrix matrix3d(multiple values): defines a matrixSets the perspective value in the element, perspective(length value), but it is somewhat different from setting it in the parent element. Because the parent element acts as perspective, while the element itself acts as perspective, leading to differences.
transform-styleflat: default value; indicates that all child elements are presented in a 2D plane preserve-3d: indicates that child elements are presented in 3D space
perspectivenone: default value; indicates an infinite angle to view the 3D object, but appears flat length value: accepts a length unit greater than 0, the unit cannot be a percentage. The larger the value, the farther the angle appears, as if you are looking at the object from a distance. The smaller the value, the opposite.Sets the position of the viewer and maps the visible content to a frustum, which is then projected onto a 2D plane; not fully understanding perspective.
perspective-originpercentage value: specifies the starting point of the element's x-axis or y-axis length value: specifies the distance left: specifies the position on the x-axis center right: specifies the position on the y-axis center bottomReference point
<div id="father">
    <img id="son" src="img.png" alt="" />
</div>

#father {
  transform-style: preserve-3d; /* Set the parent element of the 3D transformation element */
  perspective: 1000px; /* Set the viewer's distance, generally set on the parent element; combined with the following functional properties and transformation configurations, the effect can be seen */
}

#son {
  transform: translate3d(300px,100px,240px);
  transform: scale3d(1,1,1.5) rotateX(45deg);
  transform: rotate3d(1,0,0,45deg);
  /* transform: perspective(1000px) rotateY(45deg); */
  perspective-origin: top right; /* Set to the top right corner */
}

Transition Effects#

Transition Style PropertyStyle Type
background-colorcolor (color)
background-imageonly gradients (gradients)
background-positionpercentage, length (percentage, length value)
border-bottom-colorcolor
border-bottom-widthlength
border-colorcolor
border-left-colorcolor
border-left-widthlength
border-right-colorcolor
border-right-widthlength
border-spacinglength
border-top-colorcolor
border-top-widthlength
border-widthlength
bottomlength, percentage
colorcolor
croprectangle
font-sizelength, percentage
font-weightnumber
grid-*various
heightlength, percentage
leftlength, percentage
letter-spacinglength
line-heightnumber, length, percentage
margin-bottomlength
margin-leftlength
margin-rightlength
margin-toplength
max-heightlength, percentage
max-widthlength, percentage
min-heightlength, percentage
min-widthlength, percentage
opacitynumber
outline-colorcolor
outline-offsetinteger
outline-widthlength
padding-bottomlength
padding-leftlength
padding-rightlength
padding-toplength
rightlength, percentage
text-indentlength, percentage
toplength, percentage
vertical-alignkeywords, length, percentage
visibilityvisibility
widthlength, percentage
word-spacinglength, percentage
z-indexinteger
zoomnumber
PropertyvalDescription
transition-propertynone: does not support transition style property settings all: default value; all transition style properties can be set for the element Specify the transition style properties that can be setSpecifies the CSS properties for transition or dynamic simulation
transition-durationSpecifies the time required to complete the transition
transition-timing-functionease: default value, element styles transition from initial to final state from fast to slow. Equivalent to the Bézier curve (0.25,0.1,0.25, 1.0) linear: element styles transition from initial state to final state at a constant speed. Equivalent to the Bézier curve (0.0,0.0,1.0,1.0) ease-in: element styles transition from initial state to final state with acceleration. Equivalent to the Bézier curve (0.42,0,1.0,1.0) ease-out: element styles transition from initial state to final state with deceleration. Equivalent to the Bézier curve (0,0,0.58,1.0) ease-in-out: styles transition from initial state to final state, first accelerating, then decelerating. Equivalent to the Bézier curve (0.42,0,0.58,1.0) cubic-bezier(0.25, 0.67, 0.11, 0.55): custom Bézier steps(n,type): jump transition; n indicates how many jumps. type can be start or end (optional). Indicates jumping at the start/endSpecifies the transition function; determines the speed of effect changes
transition-delayDelay time before executing the transition effect after the triggering event. If there are multiple style effects, multiple delay times can be set, separated by spaces
transitionShorthand
div { /* Original style */
  width: 200px; height: 200px; border: 1px solid green;
}

div:hover { /* CSS action: :hover, :focus, :active, :checked, etc. */
  background-color: black; color: white; margin-left: 50px;

  transition-property: background-color, color, margin-left; /* Background and color as transition styles */
  /* transition-property: all */
  transition-duration: 1s;
  transition-timing-function: linear;
  transition-delay: 0s, 1s, 0s;
}

/* div:hover {
  transition: background-color 1s ease 0s, color 1s ease 0s, margin-left 1s ease 0s;
} */

/* div:hover {
  transition: all 1s ease 0s;
} */

Animation Effects#

PropertyvalDescription
animation-namenone Animation nameSpecifies the animation name, the animation name corresponds to a @keyframes rule. The animation specified by animation-name is executed when CSS loads
animation-durationThe time required for the animation to play; s or ms as the unit
animation-timing-functionease: default value, element styles transition from initial to final state from fast to slow. Equivalent to the Bézier curve (0.25,0.1,0.25, 1.0) linear: element styles transition from initial state to final state at a constant speed. Equivalent to the Bézier curve (0.0,0.0,1.0,1.0) ease-in: element styles transition from initial state to final state with acceleration. Equivalent to the Bézier curve (0.42,0,1.0,1.0) ease-out: element styles transition from initial state to final state with deceleration. Equivalent to the Bézier curve (0,0,0.58,1.0) ease-in-out: styles transition from initial state to final state, first accelerating, then decelerating. Equivalent to the Bézier curve (0.42,0,0.58,1.0) cubic-bezier(0.25, 0.67, 0.11, 0.55): custom BézierAnimation playback function
animation-delayDelay time before starting to play after the event is triggered
animation-iteration-counttimes: default value is 1 infinite: indicates infinite loopsNumber of times the animation plays in a loop
animation-directionnormal: default value, plays forward each time alternate: plays forward once, backward once, forward once, backward once alternatelyAnimation playback direction
animation-play-stateControls the playback state of the animation
animation-fill-modenone: default value; indicates that it proceeds and ends as expected forwards: after the animation ends, continue to apply the position of the last keyframe, that is, do not return backforwards: after the animation ends, quickly apply the starting keyframe position, that is, return both: produces forwards or backforwards effects according to the situationboth needs to be combined with iteration count and playback direction animation-iteration-count: 4; animation-direction: alternate;
animationShorthand for the above
@keyframesDeclare an animation, then call the animation defined by keyframes in animation
<div>I am HTML5</div>
div { /* Original style */
  width: 200px; height: 200px; border: 1px solid green;
  animation-name: myani;
  animation-duration: 1s;
  animation-timing-function: ease-in;
  animation-iteration-count: infinite;
  animation-direction: alternate;
  /* animation-play-state: paused; */
  animation-fill-mode: forwards;
}

/*
div {
  animation: myani 1s ease 2 alternate 0s both;
} */

@keyframes myani { /* Define keyframes for the animation */
    0% {
        margin-left: 0px;
    }
    50% {
        margin-left: 100px;
        background-color: black;
    }
    100% {
        margin-left: 0px;
        background-color: white;
    }
}
/* @keyframes myani {
    from {
        margin-left: 0px;
    }
    to {
        margin-left: 100px;
    }
} */

CSS Distance Measurement#

  1. px: early
  2. Percentage: The default font size of the webpage is 16px, and then set 62.5% through , setting the webpage base to 10px.
  3. em: multiple of the parent element's base.
  4. rem: multiple of the base; modern browsers recommend this measurement.
<h1>Title<em>Subtitle</em></h1>
<p> I am a paragraph, <code>I am a piece of code</code></p>

/* em */
html {
  font-size: 62.5%;
}
  h1 {
    font-size: 3em;
  }
    p {
      font-size: 1.4em;
    }

/* em */
html {
  font-size: 62.5%;
}
code {
  font-size: 1.1 rem;
}

Experimental Property Prefixes#

When new properties are introduced, these properties are still in an unstable phase and may be removed at any time. At this time, browser vendors use prefixes to implement these properties.

BrowserVendor Prefix
Chrome, Safari-webkit-
Opera-o-
Firefox-moz-
Internet Explorer-ms-

Emmet Rules#

Emmet syntax abbreviations improve the speed of writing HTML/CSS, and this syntax is already integrated into Vscode.

Element: Directly input the element name, for example, div will generate <div></div>.

Child Elements: Use > to indicate parent-child relationships, for example, div>p will generate <div><p></p></div>.

Sibling Elements: Use + to indicate sibling relationships, for example, div+p will generate <div></div><p></p>.

Parent Elements: Use ^ to indicate parent elements, for example, div>p^h2 will generate <div><p></p></div><h2></h2>. Using ^ consecutively can go up multiple levels of elements.

Repetition: Use * to indicate repetition, for example, ul>li*5 will generate an unordered list containing 5 list items.

Grouping: Use () for grouping, for example, div>(header>ul>li*2)+footer will generate a div containing a header (with an unordered list of 2 list items) and a footer.

Class Name: Use . to indicate class names, for example, div.container will generate <div class="container"></div>.

ID: Use # to indicate ID, for example, div#main will generate <div id="main"></div>.

Attributes: Use [] to add attributes, for example, a[href="https://www.google.com"] will generate <a href="https://www.google.com"></a>. Multiple attributes can be separated by spaces.

Text Content: Use {} to add text content, for example, p{Hello world} will generate <p>Hello world</p>.

Numbering: Use $ to indicate numbering, for example, ul>li.item$*3 will generate <ul><li class="item1"></li><li class="item2"></li><li class="item3"></li></ul>. You can add @- after $ for reverse numbering.

Implicit Tags: Some tags can be omitted, for example, ul>li*3 is equivalent to ul>(li*3). .container will generate <div class="container"></div>, omitting the div.

CSS basically adopts the first letter abbreviation:
For example, w200 can generate width: 200px; by pressing tab.
For example, lh26px can generate line-height: 26px; by pressing tab.

base.css#

/* Basic public styles: clear default styles + set common styles */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

li {
  list-style: none;
}

body {
  font: 14px/1.5 "Microsoft Yahei", "Hiragino Sans GB", "Heiti SC", "WenQuanYi Micro Hei", sans-serif;
  color: #333;
}

a {
  color: #333;
  text-decoration: none;
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.