current position:Home>0x02 CSS quick start

0x02 CSS quick start

2022-01-27 02:30:34 Nefu_ qky

Preface :CSS The content is miscellaneous , It is suggested to only look at the first five sections , Yes CSS Have a certain understanding ; Later, you need to use the corresponding style to retrieve ; another , The knowledge involved in this article is certainly incomplete , After all, this knowledge is too complicated , It should be updated later

One .CSS brief introduction

1. summary

CSS:Cascading StyleSheet, Cascading style sheets / Cascading style sheets , It's a course used to show HTML Document style computer language

CSS Development history of :

  1. HTML When language was invented , It doesn't matter whether the page looks good or not .

  2. With the development of the times , To meet the needs of page designers HTML Many properties for setting styles have been added in 、 Labels etc.

    <hr width="500" color="red">
    <!-- Set the length of the horizontal line 、 Color -->
    <h1>
        <font color="red">  I'm the title  </font>
    </h1>
    <!--font Labels are designed to set the font size of text 、 Color and other styles -->
    <!-- And bold labels <strong> Italics label <em> Wait, there's CSS It's useless after -->
    
  3. With the increase of function ,HTML The language itself has to be more and more bloated , therefore CSS It was born. ,CSS It realizes the separation of web page content and style , namely HTML Language is dedicated to writing the content of web pages ,CSS Adjust the style of the web page .

    When HTML When the language no longer considers the style of elements , It becomes very concise :

    <hr>
    <h1> I'm the title </h1>
    <!-- The style settings of the element are all set by CSS complete -->
    

The main function :

  • Set up HTML Text content in the page : typeface 、 size 、 Alignment, etc
  • Set up HTML The shape of the picture on the page : Wide and high 、 Border style 、 Margin, etc
  • Set up HTML The layout and other appearance display styles of the layout in the page .

To make a long story short ,CSS To change HTML The style of the web page written , Can be HTML Understand as the skeleton of a web page ,CSS Responsible for decoration and rendering

2. grammar

CSS It is composed of several sets of selectors and sound blocks

 Selectors {
	 Statement 1;  //  attribute : value ;
	 Statement 2;  // Between multiple declarations  ;  interval 
	 Statement 3;
	...
}

** Selectors :** It is used to explain whose style to modify , That is, point to the... To modify the style HTML Elements

The selector is followed by { Declaration block }, Declare the specific style to be modified in the block , Include one or more statements separated by semicolons . Each Declaration contains a CSS Property name and value , They are separated by colons .

** attribute :** Used to explain what to change , For example, to change the font size, use font-size attribute , To change the color, use color attribute

example :

h1{
     
	color:red; 
}

h1 Point to HTML In document <h1> Elements ,color Indicates that the attribute to be modified is color ,red Indicates that you want to change the color to red

Sum up , The function of this statement is to HTML All in the document <h1> Change the color of the element to red

3. Import the way

CSS Since it acts on html Document , Then we must connect them in some way .

Inline style

stay HTML In the label , use style Attribute writing CSS sentence , example :

<h1 style="color:red">  title  <h1>

But this way of writing is not recommended

Internal style

stay html Document head part , utilize style Label to define style information

stay style The label can say CSS sentence

example :

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>CSS</title>  		<!-- Webpage title -->
    <style type="text/css"> h1 {
       /* choice h1 Elements */ color: blue; /* Change the color of the element to blue */ text-align: center; /* Change the alignment of elements to center */ } p {
       /* choice p Elements */ color: red; /* Change the color of the element to red */ } </style>
</head>

<body>
    <h1> I'm the title </h1>
    <p> I am the content of the article , In order to count the number of words, you need to keep copying and pasting . I am the content of the article , In order to count the number of words, you need to keep copying and pasting . I am the content of the article , In order to count the number of words, you need to keep copying and pasting . I am the content of the article , In order to count the number of words, you need to keep copying and pasting . I am the content of the article , In order to count the number of words, you need to keep copying and pasting . I am the content of the article , In order to count the number of words, you need to keep copying and pasting . I am the content of the article , In order to count the number of words, you need to keep copying and pasting . I am the content of the article , In order to count the number of words, you need to keep copying and pasting .</p>
</body>

</html>

The effect is as follows :

The title is blue and centered , The paragraph is red

 Insert picture description here

External style

The best way to write is to CSS The code is placed in a separate file ( With .css Extension name ) in , Re pass link The tag connects it to html In the document :

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

rel yes relation Abbreviation , This attribute specifies the relationship between the document and the linked document ,stylesheet Represents linking a style sheet

href The value of is url, Specify the location of the linked document

Since there are many import methods , There is a risk of conflict . The code is executed from top to bottom , The statement executed later will overwrite the statement executed earlier , Therefore, the in-line style must have the highest priority .

4. notes

Comments are used to explain the code , It's for developers

  • The browser will ignore the content in the comment when rendering the web page

  • CSS The comment format in the code is :/* The comment */

  • stay HTML Of <style> Labels and CSS The notes in the document are in the above format

Comments can span multiple lines :

/*  This is a piece.   notes  */

Two . Selectors

The function of selector is to select / Navigate to the... You want to style HTML Elements ( Or some elements )

1. Simple selector

1) tag chooser :

according to HTML Element tag to select the element

p{
    
	text-align: center;
	color: red;
}

effect : All on page <p> All elements will be centered , And the text is red


2)id Selectors :

according to HTML Elemental id To select specific elements

Because of the elemental id It's unique in the page , therefore id Selectors are only for specific elements

Selector syntax : #id{}

#p3{
    
	text-align: center;
	color: #a13d30;
}

tips: Colors are represented by color names , It can also be represented by a hexadecimal color value


3) Class selectors :

The element selector works on all elements with the same label , The range is too wide ;id Selectors work on individual elements , The scope is too small

With <p> For example, labels , If you want to modify section 3、4、5、6、7 Duan dialect , Cannot be achieved with element selectors ,id The selector has to be operated five times and is too cumbersome .

So we can use class Property right HTML Elements are classified

notes : Class names cannot begin with numbers

<p class="center"> a paragraph </p>

stay CSS In file

** Selector syntax : ** .class{}

.center{
    
	text-align: center;
}

One HTML Elements can belong to multiple classes at the same time , example :

<p class="red center">  This paragraph falls into two categories  </p>

In the above example <p> The element will be based on red and center Make style settings

4) Universal selector :

The universal selector works on all the... On the page HTML Elements

* {
    
  text-align: center;
  color: blue;
}

2. Style priority

In a style sheet , Because multiple selectors can act on the same HTML Elements , Therefore, there may be situations where the styles of different selectors conflict . The priority of the selector is as follows :

id Selectors > Class selectors > tag chooser > Universal selector

When the selector priority is the same , The back style will overwrite the front style , example :

One HTML An element can have more than one class, these class There may be conflicts between styles in

At this time, the priority will be based on CSS In file class The location of , The one in the back will cover the one in the front

One HTML File can import multiple style sheets , Different style sheets may be the same HTML Element sets the style , The priorities are as follows :

Inline style > Internal style 、 External style > Browser default style

Internal and external styles have the same priority , Both are <head> tag , The code in the back will override the code in the front

3.HTML Structure of elements

HTML Elements can contain other HTML Elements , namely HTML Nesting of elements .

We call the nested elements as child elements 、 The external element is called the parent element . example :

<html>
	<head>
        
    </head>
    <body>
        <h1>
             I'm the title 
        </h1>
        <p>
             I'm a text 
        </p>
    </body>
</html>

<head> and <body> yes <html> Child elements

<h1> and <p> yes <body> Child elements

We can use tree structure to show the parent-child relationship between elements :
 Insert picture description here

4. Pseudo class selector

Pseudo class selectors are used to add special effects to selectors , Such as :

  • For a HTML The element is in a special state ( Such as when the mouse hovers above ) Set the style under
  • Select the first i Sub elements

Why is it called pseudo class ? Because its effect is similar to class , It's from HTML in , Select some elements that meet a certain condition .

** Selector syntax : ** : Pseudo class name {}

There are many pseudo class selectors , The following describes only the commonly used pseudo classes , The rest can be queried W3school

Link pseudo class selector

The link pseudo class selector is for the link ( namely <a> Elements ) Selector

  • :link{} : Links that have not been visited
  • :visited{} : Visited links
  • :hover{} : Mouse over link
  • :active{} : Selected links , That is, the state when the mouse clicks on the link but hasn't released it yet

Be careful :

  • a:hover Must be in CSS In the definition a:link and a:visited after , To take effect !
  • a:active Must be in CSS In the definition a:hover Before it takes effect !
  • Pseudo class names are not case sensitive .

The most common way of writing is to specify only hover The style of :

a {
    
    color: grey;		
    text-decoration: none;  // Remove underscores 
}
a:hover {
    
    color: red;
}

That is, only the style when the mouse hovers over the link is specified

Structure pseudo class selector

The structure pseudo class selector is CSS3 New features in , Depending on where the element is in the document , To dynamically select elements

The most commonly used one is :nth-child(n) , Other knowledge is enough

grammar example Example is given to illustrate
:first-child p:first-child Select all elements that are the last child of the parent element <p> Elements
:last-child p:last-child Select all elements that are the first child of the parent element <p> Elements
:nth-child(n) p:nth-child(2) Select all elements that are the second child of the parent element <p> Elements
:nth-last-child(n) p:nth-last-child(2) Select all elements that are the penultimate child of the parent element <p> Elements
:first-of-type p:first-of-type Select the first... Under all parent elements <p> Elements
:last-of-type p:last-of-type Select the last... Under all parent elements <p> Elements
:nth-of-type(n) p:nth-of-type(2) Select the second... Under all parent elements <p> Elements
:nth-last-of-type(n) p:nth-last-of-type(2) Select the penultimate of all parent elements <p> Elements
:only-child p:only-child Select all elements that are the only element of the parent element <p> Elements
:only-of-type p:only-of-type Select the unique... Under all parent elements <p> Elements

nth-child() The parameters of can be numbers 、 Keywords or a formula

  • nth-child(odd) : Choose all the odd numbered children
  • nth-child(even): Choose all the even numbered children
  • nth-child(n) : I can put n Understood as a sequence of natural numbers : 0 , 1 , 2 , 3 ⋅ ⋅ ⋅ ⋅ 0,1,2,3 \cdot\cdot\cdot \cdot 0,1,2,3, So the effect is to choose all the children
  • nth-child(2n) : When n When it is a natural number ,2n It means even number , So it's equivalent to even
  • nth-child(2n+1) : Empathy , Equivalent to an odd number
  • nth-child(3n) : Select the 3 , 6 , 9 , 12 , 15 ⋅ ⋅ ⋅ ⋅ 3,6,9,12,15\cdot\cdot\cdot\cdot 3,6,9,12,15 A child

Target pseudo class selector

The target selector is for objects with id Set by the element

Anchor jump is a very common function , Its implementation steps are as follows :

  1. Set... To an element id = new
  2. Set a link to <a href="#new"> Click the jump </a>

thus , After clicking the link, you will jump to id by new Where are the elements of

If you look closely at the address bar , You can find that at the end of the address #new

Target selector Syntax : :target { }

Select the currently active element , Active means that the user is through <a> The tag jumps to the location of the element

You can try the following small case

<!DOCTYPE html>
<head>
    <title> Target selector </title>
    <style type="text/css"> a {
       color: grey; text-decoration: none; } a:hover {
       color: red; } h2 {
       color: red; } :target {
       color: blue; font-size: 40px; } #text4:target{
       color: green; } </style>
</head>

<body>
    <p id="menu">
        <a href="#text1"> Example 1</a>|
        <a href="#text2"> Example 2</a>|
        <a href="#text3"> Example 3</a>|
        <a href="#text4"> Example 4</a>|
        <a href="#text5"> Example 5</a>
    </p>
    <h2 id="text1"> Example 1</h2>
    <br><br><br><br><br><br><br>
    <h2 id="text2"> Example 2</h2>
    <br><br><br><br><br><br><br>
    <h2 id="text3"> Example 3</h2>
    <br><br><br><br><br><br><br>
    <h2 id="text4"> Example 4</h2>
    <br><br><br><br><br><br><br>
    <h2 id="text5"> Example 5</h2>
</body>

</html>

5. compound selector

Multiple selectors , It can be combined into a composite selector in a certain way

Intersection selector

The intersection selector consists of a label selector and a class selector , example :

h3.special{
    }   /* Choose a class name of special Of h3 Elements */
p.one{
    }    /* Choose a class name of one Of p Elements */

notes : There cannot be spaces between two selectors !

This is rarely used , Not recommended

Union selector

Also known as group selector , Multiple selectors can be selected at the same time , The selectors are separated by commas , example :

h1,h2,h3,h4,h5,h5{
    } /* Choose all the title elements */
.one, p , #test {
     /* Select three elements at the same time */
    color: red;
}

If there are multiple HTML The style of the element is the same , Or part of the same , You can greatly reduce the code by grouping selectors

Descendant selector

Also called include selector , example :

p strong {
    } /* choice p Everything in the element strong Elements */

The offspring and the offspring of the offspring are descendants , That is, the selector is to select all included elements

Descendant selectors can also write many layers :

.prar .one p strong {
    } 

Descendant selector

Descendant selector , Select only child elements , example :

p > em{
    } /* Select all parent elements yes p Elemental em Elements */

The above selector , Mostly based on HTML The relationship between elements to select the , In addition to that :

  • element + element: Adjacent brother , Two element Must be at the same level and must be closely adjacent
  • element ~ element: All brothers , Two element Must be at the same level

6. Attribute selector

The attribute selector can select elements according to their attributes and attribute values .

grammar example Example explanation
[attribute] [class] Choose all with class Attribute HTML Elements
[attribute=value] [target=_blank] Select all target The attribute is _blank Of HTML Elements
[attribute~=value] [title~=flower] Select all title Property contains flower Of HTML Elements
[attribute|=value] [lang|=en] Select all lang Attribute to en At the beginning HTML Elements
⋅ ⋅ ⋅ \cdot\cdot\cdot ⋅ ⋅ ⋅ \cdot\cdot\cdot ⋅ ⋅ ⋅ \cdot\cdot\cdot

The rest can be seen Selectors

7. Pseudo element selector

Pseudo element selector syntax ::: Pseudo element name {}

The pseudo element selector is used to select a specified part of an element

Selectors describe
::first-letter Can only be applied to block level elements . Set the initial style of the text
::first-line Can only be applied to block level elements . Style the first line of text
::selection Set the style of the text selected by the user

When users browse the page , You can choose text , By default, the selected part will be displayed in white on a blue background :

image-20211129151304081

Use ::selection The selector can change the style when it is selected

In addition to the above three selectors for text , There are two very important pseudo element selectors left :

  • ::before Selectors Insert content before the content of the selected element .
  • ::after Selectors Insert content after the content of the selected element .

What exactly to insert , from content Property to specify

example :

p:before {
     
	content:" Lines :";
}

stay p Insert... At the front of the element Lines :

** notes :** The inserted content is still in p The interior of the element !!! This selector inserts the content at the front of the interior

3、 ... and . Traditional layout

CSS In fact, you don't need to learn much about the style in , What to use to search the corresponding style

But the page layout part needs to be understood , More important

Traditional layouts are based on boxed models , rely on display + position +float Property to implement

1. Commonly used labels

①span label

span Labels are used to combine inline styles , In order to format them by style

notes :span The tag itself has no format representation , The visual effect will not be produced until the style is applied

For example, you want to change a few words into orange in a jargon , You can use it span Put these words on the label , example :

<p>
	ABCDEFGHIJKLMOPQRSTUVWXYZ<br>
	<span id="promote"> Tips :</span> One letter missing 
</p>
#promote{
    
	color: orange;
	font-size: 20px;
}

②div label

div Labels and span Similar labels , No specific meaning , The difference lies in div Elements are block level elements , Monopolize one line .

div The function of tags is to combine block level elements , Style them ; Another use is for document layout

③ other

ul label 、p Tags, etc. , stay HTML Has been introduced in

2. float

float Property can make an element a floating element

grammar :float:none/left/right

none/left/right Respectively means no floating 、 Left floating 、 Right float , The default value is none

The characteristics of floating elements :

  • Exclude from normal document flow , Don't take up space in the page
  • Floating elements do not overlap each other
  • The floating element generates a block-level box , A row can have multiple block level boxes
  • Floating elements do not exceed the edge of the parent element

stay HTML In the standard flow of , The elements in the row are arranged from left to right ; Block level elements have one row exclusive , Arrange from top to bottom ;

In standard flow , It is impossible to display multiple block level elements in a row ( If two titles cannot be displayed on the same line ) Of .

Floating can be understood as floating elements above the standard flow , That is, floating elements and non floating elements can overlap each other . stay HTML In the normal layout of , There will be no coverage between elements , But floating elements can cover ordinary elements .

Even an inline element , When it is set as a floating element, it will also have width 、 High attribute , And won't monopolize one line

In a word , Floating can take elements out of the standard flow of documents , Move in the specified direction , Until it touches the boundary of adjacent floating elements or parents


clear Property to clear the float

grammar :clear:left/right/both/none

left/right/both/none Respectively indicates that floating elements are not allowed on the left of the element 、 Floating elements are not allowed on the right side of an element 、 Floating elements are not allowed on both sides of an element 、 Allow floating elements on both sides , The default value is none

Clear the meaning of floating :

  • If the parent element does not have a height set , Then its height will increase with the increase of the height of the child element ; But if there is a floating element in the parent element , Because the floating element is out of the standard flow , So that the height of the container cannot be extended automatically , Cause content overflow

  • It can also be used to wrap floating elements

Common methods of clearing floating are :

  • Add an empty... At the end div Elements , Set up clear The attribute is both: There are many meaningless empty spaces in the code div, Poor readability
  • Set the height of the parent element : Only suitable for high fixed layout
  • Define the parent element overflow:hidden

overflow Properties and height Properties cannot coexist , And there must be width attribute

After floating is cleared, the parent element can sense the height of the floating child element

3. location

Positioning through position Property to implement

grammar :position:absolute/fixed/relative/static

  • absolute: Elements use absolute positioning , be relative to static Locate the first parent element other than location
  • fixed: Elements use absolute positioning , Positioning relative to the browser window ( Even if you drag the page , Also always stay in a fixed position on the screen )
  • relative: Elements use relative positioning , Position relative to its normal position
  • static: The default value is , No location , The element appears in the normal position according to the standard flow

because static That is, do not locate the element , therefore absolute Is to locate relative to the nearest located ancestor

Positioning requires coordination top/bottom/left/right Four attributes to control the position of the element

  • top Controls the vertical distance between the upper edge of the current element and the upper edge of the positioning object

  • bottom Controls the vertical distance between the lower edge of the current element and the lower edge of the positioning object

  • left Controls the horizontal distance between the left edge of the current element and the left edge of the positioning object

  • right Controls the horizontal distance between the right edge of the current element and the right edge of the positioning object

top and bottom Choose one to use ,left and right Just choose one to use

notes : When position The property value is static when , All four properties are invalid

relative It refers to the current position , Move a specified distance . It should be noted that , In the use of position:relative After changing the position of the element , The original position of the element is still occupied , The purpose of this setting should be to not affect the layout of other elements

absolute The reference object of is complex . It should be noted that the position:absolute The element of the document will be separated from the document flow . But it and use float Property is different from document flow , The main difference is that float Just half detached , Other texts will still avoid float Elements ; and absolute Will not be avoided

relative The original physical location of the element is still occupied ,absolute Will not occupy the original physical location !

 Insert picture description here

fixed It is positioned with the browser window as the reference object . When the browser window size changes 、 Or when the user scrolls the page position:fixed The element of will always appear in a fixed position


position Property sets the plane position of the element ,z-index Can be used to set the element in z Position on the shaft

When several elements overlap ,z-index Attributes can determine who is on top 、 Who's down there

grammar :z-index:number

z-index The default value is auto( And the parent element z-index The values are equal ) IE Under the browser z-index The default is 0

For the two z-index Elements of the same value , The element defined later will overwrite the element located earlier ( The child element overrides the parent element )

notes :z-index Property only supports the use of... For positioning elements !( It's not static Elements )

4.display attribute

according to CSS standard , Every web element has display attribute , Used to determine the type of element . Such as div The default value of the element is block( Block-level elements ),span The default value of the element is inline( Inline elements )

display Common attribute values :

  • none: Hidden elements
  • inline: Inline elements / Inline elements
  • block: Block-level elements
  • inline-block: Inline block element / Inline block elements

inline For in-line elements , Does not have the width and height attribute , And don't monopolize one line ;

block Is a block-level element , With width and height attribute and exclusive row

inline-block Elements have width and height attributes , But not exclusive , And floating elements ( Use more ) More like

display:none You can hide elements , It should be noted that there are two similar properties

  • visibility:hidden/visible: Make elements invisible / so
  • opacity:0: Set element transparency to 0

Use these two methods to hide elements , Even if the element is invisible, it still occupies the original physical space

display:none Does not occupy the original physical space .

5. Box model

stay CSS in , You can take all HTML Elements are treated as boxes :

 Insert picture description here

  • Margin( Margin ) - The area outside the border , The outer margin is transparent .
  • Border( Frame ) - The border around the inside margin and the outside of the content .
  • Padding( padding ) - Clear the area around the content , The inside margin is transparent .
  • Content( Content ) - The contents of the box , Show text and images .

Setting the element's width、height Attribute , Just set the width and height of the content area of the box ;

HTML The actual width of the element is greater than width Wider , Therefore, when making the header, you can find , If you don't make the element margin by 0, The element is always at a distance from the edge of the browser window


Margin:

margin Property sets the outer margin of the element , The default value is 0, There is no inheritance

The value can be auto,%, negative

Setting mode :

margin-top:10px;
margin-bottom:10px;
margin-left:10px;
margin-right:10px;

↑ Set the upper margin of the elements respectively 、 Bottom margin 、 The left margin 、 The right margin

margin:10px 5px 15px 20px

↑ The four parameters set the upper margin of the element respectively 、 The right margin 、 Bottom margin 、 The left margin ( Clockwise order )

margin:10px 5px 15px;

↑ The top margin is 10px, The left and right margins are 5px, The bottom margin is 15px

margin:10px 5px;

↑ The top margin and bottom margin are 10px, The left and right margins are 5px

margin:10px;

↑ All outer margins are 10px

margin Property can be used to implement Blocky element In the middle of :

margin: 0 auto;

Centering up and down cannot be realized automatically , Can only use top Properties to adjust

In massive elements Text 、 Inline elements 、 The center of the block element in the row , Can pass text-align:center Statement to adjust ;

Characteristics of outer margin :

  1. There is a problem of merging the upper, lower and outer spacing of the box

    example : The bottom margin of an element is 100px, The upper margin of the following element is 50px, Then the actual distance between the two is only 100px( Taking the maximum )

  2. In line elements have no upper and lower outer margins , Only left and right outer margins ( And will not merge )

  3. The outer margins of floating elements do not merge

  4. Negative outer margins are allowed


Border:

The border of the box has three elements : wide 、 style 、 Color

Use them separately border-width、border-style and border-color Property to specify

It can also be used uniformly style Property to specify , Generally in width 、 style 、 Write in the order of colors , example :border:1px solid red;

The style of the border : The default value is none

  • dotted: Punctate
  • solid: Solid line
  • double: double ( You need to set the width to at least 3px, Otherwise... Will not be displayed )
  • dashed: Dotted line
  • none: no border

The width of the border : The default value is 3px

Color of border : The default value is black

Make , You can set the border on one side separately :

  • border-right:5px solid red;
  • border-left-style:solid; border-left-width:5px;

Padding:

The inner margin and outer margin are written in the same way , I won't repeat

It should be noted that ,Padding、Border It's all part of the box ,Margin It is not

such as :

div{
    
	background-color:red;
	height:200px;
    width:200px;
	border:5px;
	padding:20px;
}

Then this red div Elements , The actual width is 200+2*5+2*20=250px

In other words ,background-color This attribute can be applied to the inside margin and border


Weird box model :

IE Box model in browser , wide (width attribute ) It includes width and padding

We can use box-sizing Attribute to change the box model of an element

  • box-sizing:content-box Standard box model
  • box-sizing:border-box Weird box model

In the weird box model width How much? , What is the width of the box

The width of the box in the standard box model is width+padding+border

Four . Elastic layout

1. summary

The elastic box is CSS3 A new layout pattern of .

CSS3 Elastic box ( Flexible Box or flexbox), It's a way when the page needs Adapt to different screen sizes and device types A layout that ensures that elements have appropriate behavior when , Provides a more efficient way to arrange the child elements in a container 、 Align and allocate white space .

By way of display Property value set to flex or inline-flex You can make HTML The element becomes an elastic container

flex There are two shafts in the container : Spindle (main axis) And side shaft (cross axis)

 Insert picture description here

flex All items in the container ( Subelement ) Arranged in a row according to the main axis

This effect and float More like , But more flexible

2.flex

The traditional layout divides a box into three parts :

section div {
     /* The parent element is section  The three sub elements are div*/
    width: 33.33%;
    height: 100%;
    float: left; 
}

If it is required to change the spacing of three sub elements , You need to recalculate width value , so much trouble

Flexible layout :

  1. Make the parent element an elastic container : display:flex;
  2. Child element settings : height:100%;flex:1;

flex The attribute value defines the space occupied by each child element , Because all child elements are 1, And for 3, So each element accounts for 1 3 \frac{1}{3} 31

At this point, even if you add more spacing to the child elements :margin: 0 5px, Can still maintain the state of trisection

If child element 1 Set to flex:1 , Subelement 2 Set to flex:2, Subelement 3 Set to flex:3, Then the three elements account for 1 6 \frac{1}{6} 61 1 3 \frac{1}{3} 31 1 2 \frac{1}{2} 21

If child element 1 Set to fixed width width:300px, Then the remaining two elements will be allocated proportionally according to the remaining space

It's the same as assigning a percentage to the width of an element , This kind of writing is also responsive . But in order not to make the element too narrow to see the content , You can use properties min-width Limit the minimum width of the element , Empathy max-width Limit the maximum width

3.flex-direction

flex-direction Property can change the direction of the elastic container spindle

value describe
row The default value is . Flexible items will be displayed horizontally , Just like a line .
row-reverse And row identical , But in reverse order .
column Flexible items will be displayed vertically , Just like a column .
column-reverse And column identical , But in reverse order .

reference Desert ghost Pictures of the , To feel more intuitively :

  1. row( The default value is ): The principal axis is horizontal , The starting point is at the left end of the container .
     Insert picture description here

  2. row-reverse: The principal axis is horizontal , The starting point is at the right end of the container .
     Insert picture description here

  3. column: The principal axis is perpendicular , The starting point is on the top edge of the container .
     Insert picture description here

  4. column-reverse: The principal axis is perpendicular , The starting point is at the bottom of the container .
     Insert picture description here

4.flex-wrap

By default, all items in the elastic container ( Subelement ) All on the same line ,flex-wrap Define how to wrap a line if it doesn't fit

notes : Set the minimum width for the element 、 A fixed width may result in a row that cannot hold all child elements

value describe
nowrap The default value is . Don't wrap , Direct spillover
wrap The overflow part starts with another line
wrap-reverse The overflow part occupies the first line
  1. nowrap( Default ): Don't wrap .
     Insert picture description here

  2. wrap: Line break , The first row is at the top .
     Insert picture description here

  3. wrap-reverse: Line break , The first row is at the bottom .
     Insert picture description here

flex-direction Properties and flex-wrap Attributes can be abbreviated as flex-flow attribute , The default value is row nowrap.

5.justify-content

justify-content Defines the alignment of the item on the spindle .

value describe
flex-start The default value is . The beginning of the line is aligned with the starting position of the spindle
flex-end The end of the line is aligned with the end of the spindle
center center alignment
space-between Arrange evenly spaced
space-around The clearance on both sides of each item is the same
  1. flex-start: Align to the starting position of the spindle , That is to say, the arrangement starts from the starting position of the main shaft .

flex-start

  1. flex-end: Align to end of spindle , That is, the arrangement starts from the end of the main shaft .

flex-end

  1. center: In the middle

center

  1. space-between: If there are more than two projects , The start and end positions of the main shaft of the container are respectively one , Other items are arranged evenly , The interval between items is equal . If there is only one item, it is only arranged at the beginning of the main shaft of the container
     Picture description here
     Picture description here
     Picture description here
  2. space-around: The spacing between each item is equal . therefore , The spacing between items is twice as large as the spacing between items and the border . The order is the same as flex-direction of . If only one item is in the middle .
     Picture description here
     Picture description here
     Picture description here

6.align-items

All items in the elastic container are arranged along the main axis ,align-items Define the position of the item on the vertical axis

value describe
flex-start Align the starting point of the project and the side axis .
flex-end The end points of the project and the side axis are aligned .
center The item is located at the midpoint of the side axis .
baseline Baseline alignment of the first line of text for the project .
stretch The default value is , If the project has no height or is set to auto, Stretch the child element to the height of the entire container .
  1. flex-start: Align the starting point of the project and the side axis .
     Picture description here
  2. flex-end: The end points of the project and the side axis are aligned .
     Picture description here
  3. center: The item is located at the midpoint of the side axis .
     Picture description here
  4. baseline: Baseline alignment of the first line of text for the project .
     Picture description here
  5. stretch( The default value is ): If the project is not set to height or set to auto, Will fill the entire container .
     Picture description here

7.align-content

There may be multiple spindles in the elastic container , This is in flex-wrap Property

align-content Property can define the non coaxial arrangement , It doesn't work when there is only one axis

value describe
flex-start Align with the starting point of the side axis .
flex-end Align with the end of the side axis .
center Located at the midpoint of the side shaft .
space-between Align with both ends of the side shaft , The average distribution of spacing between axes .
stretch The default value is , Stretch multiple rows to cover the entire side axis .
space-around The spacing between each axis is equal .
  1. stretch( The default value is ): Multiple rows occupy the entire side axis .
     Picture description here
  2. flex-start: Align with the starting point of the side axis .
     Picture description here
  3. flex-end: Align with the end of the side axis .
     Picture description here
  4. center: Align with the midpoint of the side axis .
     Picture description here
  5. space-between: Align with both ends of the side shaft , The average distribution of spacing between axes .
     Picture description here
  6. space-around: The spacing between each axis is equal . therefore , The spacing between the axes is twice as large as the spacing between the axes and the borders .
     Picture description here

5、 ... and .CSS The three major characteristics

1. Layering

Lamination refers to a variety of CSS Style overlay

Style conflict : When an attribute of an element , When specified by two styles at the same time , One style will overwrite the other

When styles conflict , Take the principle of proximity , therefore :

Inline style > Internal style 、 External style > Browser default style

The external style is through <link href="..."> Imported , The internal style is through <style> The label is written , Who is HTML The document is close to the target element , Who can cover each other . Because the style writing is before the elements , So whoever writes in the back can cover each other

And if it's the same inline style / Internal style / External style , The principle of proximity is still adopted , example :

<style> p {
    
		color:red;
	}
	p {
    
		color:blue;
	}
</style>

Final p The text in the label appears blue

Of course, the principle of proximity is not absolute , Different selectors in the same style sheet , You have to obey another law

id Selectors > Class selectors > tag chooser > Universal selector

<head>
	<style type="text/css"> #t {
       color: red; } p {
       color: blue; } </style>
</head>
<body>
	<p id="t">
		 Cheerleading 
	</p>
</body>

Final p The text in the label appears in red

therefore , We can think so : The browser executes by line HTML Document , So the latter will cover the former ; And the styles in the same style sheet , Will be dealt with uniformly , therefore id Selectors take precedence over other selectors even if they are written first

2. inheritance

inheritance , refer to HTML The child element inherits some styles of the parent element , example :

<head>
	<style type="text/css"> div {
       color: red; } </style>
</head>
<body>
	<div>
		<p>
			hahaha
		</p>
	</div>
</body>

although p The label is not assigned any style , But the text will still appear in red

The situation of inheritance is more complex , Some attributes may be inherited and some may not ; For the same attribute, some tags can inherit while others will not

A classic example is a label , Will not inherit the parent element color value

Attribute value inherited from parent element , In case of style conflict, it will be overwritten .

3. priority

Priority specifies the priority between selectors , That is, the solution when style conflicts occur in the same style sheet

id Selectors > Class selectors > tag chooser > Universal selector This prioritization is rough , Because there are probably styles formed by the combination of multiple selectors in the style sheet , example :

<head>
    <style type="text/css"> div p a{
       color: red; } p a {
       color: black; } </style>
</head>
<body>
    <p>
        <a class="more">ttt</a>
    </p>
</body>

The final execution is red

Style inherited from parent element , Contribution: 0.0.0.0

The contributions of tag selectors and pseudo element selectors are :0.0.0.1

The contributions of class selectors and pseudo class selectors are :0.0.1.0

id The contribution of the selector is :0.1.0.0

The contribution of inline styles is :1.0.0.0( Inline style is equivalent to a selector )

This string of four numbers , Equivalent to four bits : Such as 0.1.0.0 Priority is greater than 0.0.1000.0

Each selector may be a combination of multiple selectors , At this time, the contribution values of different selectors will be superimposed , Such as :

a{
     color:red;} /* 0.0.0.1 */
p a{
     color:blue;} /* 0.0.0.2 */
div p a{
    color:red;}  /*0.0.0.3*/
p a.more{
     color:green;} /* 0.0.1.2 */

Besides, there are !important Command representation is extremely important , It must be carried out , example :

h1{
     color:red!important;}

When the weight of different selectors / When the contribution is the same , Using the principle of proximity

example 1 :
 Insert picture description here

answer : Blue

explain : Although there are !important, But the weight of inheritance is 0, so #father #son The weight for 0.2.0.0 The highest

example 2:

 Insert picture description here

answer : yellow

explain : First, all three selectors can locate the container where the text is located , No need to consider inheritance ; Calculating the weight is div #box3 and #box1 div Tied for the highest , At this time, the principle of proximity is adopted , So the final color is yellow

6、 ... and . typeface

Chrome The default format of Chinese font is Microsoft YaHei 、16 Font number :

 Insert picture description here

font-family: typeface

stay CSS in , We use font-family Property specifies the font of the text . example :

font-family: "microsoft_yahei";   // Set the font attribute to Microsoft YaHei 

We can also specify the font in Chinese :

font-family: " Microsoft YaHei ";

But Chinese coding has two defects :

  • File encoding may not match
  • This writing was not supported in earlier systems

Therefore, it is more recommended to use the corresponding English name to specify the font

font-family Attribute can contain multiple fonts at the same time , There should be a space between font names Separated by commas

font-family: "SimSun","microsoft_yahei","Serif";

This is done to ensure that web pages and browsers / Compatibility between operating systems . The priority in front is high , If the browser can't recognize the font in front, it will automatically look for the appropriate font back .

stay CSS in , There are five generic font families :

  • Serif font (Serif)
  • Sans serif fonts (Sans-serif)
  • Equal width font (Monospace)
  • Cursive script (Cursive)
  • Fantasy font (Fantasy)

All different font names belong to one of these five general font families . These five font names do not need to consider compatibility , So it is recommended that font-family Put the general font at the end of the .

font-family Property has inheritance , That is, the default font is the same as that of the parent element

font-style: Italics

font-style It is mainly used to define italic text , The possible values are :

  • normal: The default value is , Display a standard font style by the browser
  • italic: italics
  • oblique: tilt , Very similar to italics
  • inherit: Specifies that the style is inherited from the parent element

font-weight: The font size

font-weight Used to define the thickness of the font , The possible values are :

  • normal: The default value is , Standard characters
  • lighter: Finer characters
  • bold: Bold characters
  • bolder: Thicker characters
  • {100,200,,,900}: Defined by numbers ,400 be equal to normal,700 be equal to bold
  • inherit: Specifies that the style is inherited from the parent element

font-size: font size

font-size Is a property used to set the font size

font-size The value of can be absolute size or relative size :

  • Absolute size sets the text to the specified size , Users are not allowed to change the text size ( Poor accessibility )
  • Relative size is the size relative to the surrounding elements

The default size of text is 16px

① Set the font size in pixels

Pixels are absolute units , example :

h1 {
    
  font-size: 40px;
}

② use em Set font size

em It's a relative unit , Is the size of the current element relative to the font of the parent element ;

for example : Parent element font-size: 32px , Subelement font-size: 1em , The font size of the child element is also 32px

If the font size is not set in the parent element , That is, it is equivalent to using the default size 16px, example :

body{
    
	font-size: 25px;
}
p{
    
	font-size: 1em;
}
span{
    
	font-size: 2em;
}

③ Set the font size in percentage :

Percentage is also a relative unit , and em The effect is the same

Although the Internet says em It's different from percentage , But there is no specific statement

The best way to write it is in body Set the font size with 100% in , It's used everywhere else em:

body{
    
	font-size: 100%;
	font-family: KaiTi,NSimSun,SimHei,SimSun;
}
p:first-of-type{
    
	font-size: 0.5em;
}
p:nth-of-type(2){
    
	font-size: 2em;
}
p:last-of-type{
    
	font-size: 1.3em;
}

④ Responsive font size :

We can use units vw(viewport width, Viewport width ) To set the text size

The text size will be scaled according to the browser window size

1vw Equal to... Percent of the width of the current viewport 1

font: Font attribute abbreviation

To shorten the code , Can be in font Specify the values of all other attributes in the attribute

In that order font-style、font-weight、font-size、font-family ( The order cannot be changed )

body{
    
	font:italic bolder 32px KaiTi;
}

font-style and font-weight It can be omitted

body{
    
	font: 32px KaiTi;	
}

7、 ... and . Text

color: text color

color Property is used to specify the color of the text . The possible values are as follows :

value describe
color_name Color name , Such as red、blue、purple、orange etc.
hex_number Hexadecimal value , Such as : #ff0000、#000000( black )、#ffffff( white )
rgb_number rgb Code , Such as : rgb(255,0,0)
inherit Inherit color from parent element .

rgb It's a color standard in industry , adopt R( Red )、G( green )、B( Blue ) The superposition , You can get almost all the colors that people can perceive .

RGB Each has 256 Levels of brightness , from 0、1、2… until 255. A total of about 1678 Thousands of colors , namely 256 × 256 × 256 = 16777216 256×256×256=16777216 256×256×256=16777216

Hexadecimal values are right RGC A representation of color , Every two hexadecimal bits can represent RGB One of the parameters in

For example, red can be expressed as rgb(255,0,0), It can also be expressed as #FF0000

Translucent colors :

This is a CSS3 New features in

grammar :color: rgba(r,g,b,a);

among a a a Presentation transparency , The value is 0 To 1 Between . When a a a by 0 when , Highest transparency , The text is transparent and invisible .

text-align: Horizontal alignment

text-align Attribute specifies the horizontal alignment of the text in the element .

value describe
left Arrange the text to the left .
right Arrange the text to the right .
center Align center , Put the text in the middle .
justify Achieve the effect of text alignment .
inherit Rules should be inherited from the parent element text-align The value of the property .

full-justified : The left and right ends of the text line are placed on the inner boundary of the parent element . Then adjust the spacing between words and letters. , Make the lines exactly equal in length .

line-height: Row spacing

line-height Property to set the distance between lines ( Row height ).

The specific setting of this property is complex , Just a little bit more . When using, use pixel value to set , Just adjust the size of the row height according to the effect

text-indent: The first line indentation

text-indent Attribute specifies the indent of the first line of text in a text block .

In real life , The first line of a paragraph needs a few spaces , This is the first line indent .

Generally, this value is set to 2em, namely text-indent:2em,2em Is the width of two Chinese characters

letter-spacing: Space between words

letter-spacing Property is used to define character spacing , That is, how much space is inserted between text character boxes .

The default value of this property is 0

notes : Allow negative values , Make the characters closer

word-spacing: Word spacing

This is an attribute for English , Because there is no concept of words in Chinese , Chinese paragraphs are made up of words .

So this attribute doesn't work for Chinese .

text-shadow: Text shadow

text-shadow Property to shadow text , Used to increase the three-dimensional feeling of text

grammar :text-shadow: h-shadow v-shadow blur color;

You need to set the values of four parameters :

Parameters value
h-shadow It's necessary . The position of the horizontal shadow . Allow negative values .
v-shadow It's necessary . The position of the vertical shadow . Allow negative values .
blur Optional . Fuzzy distance .
color Optional . Color of shadow .

The values of the first three parameters are in px In units of ,color The value of the parameter and color Property is set in the same way

8、 ... and . background

Add a background picture to the web page 、 Color

attribute describe
background-color Add background color
background-image Add background image
background-repeat Specify the filling method of the background picture
background-position Specify the location of the background picture
background-attachment Specifies whether the background image scrolls with the page

background-image

background-image Attribute can add a background image to the element .

grammar :background-image: url(" Path of the picture ");

By default , The image will be tiled to cover the entire element .

Such as : The picture is high 300px , wide 300px; Add it to a high 300px, wide 400px Of div In the elements , In order to cover the whole element , The picture will repeat , Like this effect :

 Insert picture description here

background-repeat

background-repeat Property specifies how the background picture is filled

Possible value describe
repeat-x Tile horizontally
repeat-y Tile vertically
repeat The default value is , The transverse 、 Tiled vertically
no-repeat Don't spread

background-position

Don't spread , The background image cannot cover the whole element , Areas not covered are displayed as background colors

 Insert picture description here

background-position You can specify the position of the background picture at this time

grammar :

  • Use two location nouns to specify the location , Such as :left top;right bottom;center bottom etc.
  • Specify the position with a percentage or pixel value , Such as :10px 30px10% 20px, The former represents the position from the left end of the parent element , The latter represents the position from the top of the parent element

background-attachment

background-attachment Property specifies whether the background image should be scrolled or fixed ( Does not scroll with the rest of the page )

The duty of fixed when , The background image doesn't scroll as the page scrolls

The default value is scroll , Indicates that the background picture will scroll

background: Attribute shorthand

To shorten the code , It can also be in an attribute background Specify all background properties in . It's called the abbreviated attribute .

When using abbreviated attributes , The order of attribute values is :

  • background-color
  • background-image
  • background-repeat
  • background-attachment
  • background-position

It doesn't matter if one of the attribute values is missing , Just set other values in this order . example :

body {
    
  background: #ffffff url("tree.png") no-repeat right top;
}

background-size

CSS3 New features in , Used to zoom the background picture

grammar :

  1. background-size: 80% Scale the picture to 80% of the original
  2. backgournd-size:100px Specifies the width of the background picture , And scale it proportionally , If the width of the original drawing is 300px Is reduced to 1/3
  3. background-size:400px 500px Specifies the width of the background picture 、 high , May cause image distortion
  4. **background-size:cover** Automatically adjust the zoom scale so that the picture is covered with the background , It's proportional scaling, so it doesn't distort , The overflow part is hidden .( Because the width and height meet the needs of the box , It is bound to cause one dimension to exceed the box )
  5. background-size:contain It's also scaling , But make sure the picture is displayed completely

background:size and background-size:contain It's all about scaling the picture proportionally , The former stops zooming when the width and height reach the needs of the box , And hide the overflow ; The latter stops scaling when one of the width and height reaches the need of the box , So no overflow will be hidden , But it will not cover the background

Nine . Animation

transition: transition

transition : Add effects when elements switch from one style to another .

When the attributes of an element change , Such as width from 100px Change to 300px

 Insert picture description here

This change is very abrupt ,transition Attributes can make the state of an element change more smoothly

attribute describe
transition Abbreviations for the four transition attributes
transition-property Define transition properties , Define which attribute to achieve the transition effect , The default value is all
transition-duration Define the time spent on transition effects , The default value is 0. The unit is s or ms
transition-delay Define how long to wait before starting the transition , The default value is 0
transition-timing-function Define the speed curve of the transition effect , The default value is ease

take transition-duration Set to 2s after :

 Insert picture description here

transition-timing-function Possible value of :

value describe
linear Specifies the transition effect from start to end at the same speed ( be equal to cubic-bezier(0,0,1,1)).
ease Set a slow start , And then it gets faster , Then the transition effect of slow ending (cubic-bezier(0.25,0.1,0.25,1)).
ease-in Specify the transition effect starting at a slow speed ( be equal to cubic-bezier(0.42,0,1,1)).
ease-out Specify the transition effect ending at a slow speed ( be equal to cubic-bezier(0,0,0.58,1)).
ease-in-out Specify transition effects starting and ending at a slow speed ( be equal to cubic-bezier(0.42,0,0.58,1)).
cubic-bezier(n,n,n,n) stay cubic-bezier The function defines its own value . The possible value is 0 to 1 Value between .

transition Attribute syntax :transition: property duration timing-function delay;

transform:2D deformation

transform Attribute can realize the displacement of the element 、 rotate 、 tilt 、 The zoom

grammar :transform: none|transform-functions; Through different transform-function To achieve different change effects

notes :transform Attributes need the help of transition To achieve animation , Otherwise, there will also be “ Abrupt ” sense

  1. Element displacement

    value describe
    translate(x,y) Realize the displacement of elements 、 Move
    translateX(x) Only in x Axis direction .
    translateY(y) Only in y Axis direction

    example :transform:translate(100px,100px)

    notes 1: If only one parameter is written, it is only in x Axial movement

    notes 2: if x、y If the value is negative, it will be left 、 Upward displacement ; If it is regular right 、 Lower displacement

    notes 3: If the moving distance is not px In units of , But rather % In units of , Then this refers to the percentage of its own width

    So there is a wonderful way to write in the middle :left:50%;top:50%;transform:translate(-50%,-50%);

  2. Scaling of elements

    value describe
    scale(x,y) Realize the scaling and conversion of elements .
    scaleX(x) Achieve horizontal scaling
    scaleY(y) Achieve vertical scaling

    example :transform:scale(1.2,1.5) // Scale horizontally 1.2 times , Zoom vertical 1.5 times

    notes 1: If only one parameter is written, the level 、 Scale vertically by the same factor

    notes 2: Such as magnifying a photo , And subtract the overflow , It can achieve the effect of zooming in the lens :

    • div{overflow:hidden;} as well as div:hover img{transform:scale(1.2);}
  3. Rotation of elements

    value describe
    rotate(angle) Realize the rotation of elements

    example :transform:rotate(90deg) // Clockwise rotation 90 degree

  4. **transform-origin:** Set the base point of element deformation

    For example, in rotation , Defines the point around which the element rotates ( The default is the center point )

    grammar :transform-origin: x-axis y-axis z-axis;

    The default value is :transform-origin: 50% 50% 0;

    Possible values :

    • x-axis:left、right、center、 Pixels 、 percentage ( The latter two are based on the distance in the upper left corner )
    • y-axis:top、bottom、center、 Pixels 、 percentage

    example :transform-origin: left top; Based on the upper left corner

transform:3D deformation

pigeon ing

copyright notice
author[Nefu_ qky],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270230146590.html

Random recommended