CSS basics is enough

CSS basics is enough [Guide]

This chapter mainly sorts out some basic knowledge of CSS. Before we start, take a quick quiz:

  • What are the import methods of CSS?
  • :root #myApp input:requiredWhat is the weight?
  • Can the a element inherit the color of the parent element, and what about the width?
  • Do you know CSS variables?

Write your answer in the comment area first, and see how many you can answer.

introduction of styles

There are three ways to introduce CSS: inline styles, internal style sheets, and external style sheets.

inline style

Inline styles are also called inline styles. Inline styles are styled through the styleattribute , as follows:

<h1 style="color:red;">style 属性的应用</h1>
<p style="font-size:14px;color:green;">直接在 HTML 标签中设置的样式</p>
<p style="display:none;">影藏的内容</p>

Inline styles have a higher priority and can be used to set some special styles or fine-tune the style of elements. It is not recommended to put all the styles in the inline style sheet, because too many styles will make the elements "bloated", making the document structure of the document unclear and not conducive to maintenance.

internal style sheet

An internal style sheet is to write styles inside a styletag :

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>内部样式表</title>
  <style>
    h1 {
    
    
      color: red;
    }

    p {
    
    
      font-size: 14px;
      color: green;
    }
  </style>
</head>

<body>
  <h1>style 属性的应用</h1>
  <p>直接在 HTML 标签中设置的样式</p>
</body>

</html>

The way of internal style sheets realizes the separation of structure and style. The advantage of this is that HTML focuses on building web page structure, while CSS focuses more on adjusting element styles. This method is very useful when learning or demonstrating CSS properties, or it is very convenient when debugging a small function. At present, some front-end frameworks use this method, such as Vue and Svelte. This way of writing is not friendly enough when dealing with large-scale websites, because large-scale websites have many pages and many CSS styles can be shared. If each page has to be rewritten or manually assigned, that feeling is quite painful. So there is a separate CSS file.

external style sheet

An external style sheet refers to writing the style in a separate style file, and then referencing it through the file path:

<link rel="stylesheet" href="reset.css">
<link rel="stylesheet" href="utils.css">
<link rel="stylesheet" href="main.css">

Write the style separately in the style file, which can be imported through linkthe tag . When modifying, you only need to modify it once, and all web pages that depend on this file will take effect. In addition, you can also publish your own style sheets on the Internet in the form of libraries, which can also be referenced by other websites in need, which is really not too convenient.

CSS selectors

Writing the style in the style sheet (in stylea tag or a separate style file) needs to solve a problem: who is this style written for, or who needs this style, if the style must be made into all kinds of clothes, then give the element The process of applying styles is like putting on clothes. The process of dressing is the process of applying styles. CSS applies styles to elements through CSS selectors.

label selector

The tag selector selects tags by element tag name, for example:

h1 {
    
    
  color: red;
}

will set the font color of all h1 tags to red.

id selector

The id selector will select tags with an id value:

<style>
  #tom {
      
      
    color: grey;
  }

  #garfield {
      
      
    color: orange;
  }
</style>

<h1 id="tom">我是汤姆猫</h1>
<h1 id="garfield">我是加菲猫</h1>

The grammatical format of the id selector is #id-name, generally speaking, the id is unique in a web page, what happens if there are two elements with the same id value? That is, all elements with that id value will wear the corresponding style.

class selector

The class selector applies the corresponding style through classthe attribute , and its declaration method is:

<style>
  .grey {
    
    
    color: grey;
  }

  .orange {
    
    
    color: orange;
  }
</style>

<h1 class="grey">我是汤姆猫</h1>
<h1 class="orange">我是加菲猫</h1>

Class selection is done by .class-namedeclaring class styles, which can be combined:

<style>
  .grey {
    
    
    color: grey;
  }

  .orange {
    
    
    color: orange;
  }

  .underline {
    
    
    text-decoration: underline;
  }
  
  .small{
    
    
    font-size: 14px;
  }
</style>

<h1 class="grey underline">我是汤姆猫</h1>
<h1 class="orange small">我是加菲猫</h1>

Each style has its own unique effect, and a complex effect can be achieved by combining different styles, just like a girl's outfit: lipstick looks mature, a necklace looks rich, a bow looks cute, and stockings look chic Sexy, you can match any style with whatever effect you want, so girls especially like to learn the front end, right?

attribute selector

Attribute selectors can select elements with certain attributes, the syntax is as follows:

<style>
  [hello] {
    
    
    color: green;
  }
</style>

<h1 hello>我是汤姆猫</h1>
<h1>我是加菲猫</h1>

Of course, you can also set the attribute value:

<style>
  [hello=world] {
    
    
    color: green;
  }
</style>

<h1 hello="world">我是汤姆猫</h1>
<h1 hello>我是加菲猫</h1>

More powerful selector 1 :

/* href 中含有 "example" */
a[href*="example"] {
    
    
  font-size: 2em;
}

/* href 以 ".org" 结尾 */
a[href$=".org"] {
    
    
  font-style: italic;
}

/* 样式表包含 "logo" */
a[class~="logo"] {
    
    
  padding: 2px;
}

/* href 包含 "insensitive" 忽略大小写,与正则开关类似 */
a[href*="insensitive" i] {
    
    
  color: cyan;
}

descendant selector

In addition to selecting an element individually, you can also select through the nested relationship between elements, the most commonly used is the descendant selector:

<style>
  .summer .plant {
    
    
    color: green;
  }

  .autumn .plant {
    
    
    color: gold;
  }
</style>

<div class="summer">
  <div class="plant">玉米</div>
</div>

<div class="autumn">
  <div class="plant">玉米</div>
</div>

Adding a space between two independent selectors means: what is in what, or in other words, the descendants of who and so and so and so. Anyway, the space indicates the descendant relationship, and it is also possible to be separated, as long as it is inside, it will take effect. The example above shows that the plants in summer and the plants in autumn are each in the same style.

direct child selector

The syntax for direct child selectors is parent>child:

<style>
  .summer>.plant {
      
      
    color: green;
  }

  .autumn>.plant {
      
      
    color: gold;
  }
</style>

<div class="summer">
  <div class="north">
    <div class="plant">玉米</div>
  </div>
</div>

<div class="autumn">
  <div class="plant">玉米</div>
</div>

It doesn't work if the generation is separated, it must be a direct child node.

Brotherhood

Adjacent sibling selector one+two+three:

<style>
  .one+.two {
      
      
    color: red;
  }

  .two+.three {
      
      
    color: green;
  }

  .one+.three {
      
      
    color: blue;
  }
</style>

<div class="box">
  <div class="one">大娃</div>
  <div class="two">二娃</div>
  <div class="three">三娃</div>
</div>

Pay special attention to the fact that there is a second baby between the eldest baby and the third baby, and the blue color of the third baby will not take effect.

summary

The above section summarizes some commonly used selectors. There are too many CSS selectors. For more selectors, please read reference article 2 .

[Exercise] How to select all child nodes except the first one?

ul li:not(:first-child){
    
    ...}

CSS selector priority

CSS (Cascading Style Sheets) cascading style sheets, an element may be selected by multiple style rules at the same time, such as wildcard *, tag name, class, which style should the browser use? At this time, you need to set the style according to the priority. Open the browser debugging tool, the style of the element will be displayed in the Styles column, and the style with a high priority will be displayed on the top, and the style with a low priority will be displayed below, and many of the same style attributes will be crossed out , this is because the higher-priority styles override the lower-priority styles:

insert image description here

[Knowledge points] Style weights are divided into three levels: ID, Class, Type 3 , so the style weights applied to an element are: 1-1-1.

【Example】ul#nav li.active aThe weight is: 1-1-3, which has an ID selector #nav, a Class selector .active, and three Type selectors: ul, li, a.

[Knowledge Points] Style weight calculation rules, comparing priorities from high to low.

[Example] 1-3-2Greater than 1-3-1, first compare ID: 1==1, then compare Class: 3==3, and then compare Type: 2>1.

What are the selectors for each level?

  • ID level . Only one: #id, weights:1-0-0
  • Class level . 1) class .class, 2) attribute: [attr], [attr=value], [lang|="zh"], 3) ​​pseudo-class: :hover, :nth-of-type(3n), :required , weight:0-1-0
  • Type level . 1) Tag name: div, p , a, 2) Pseudo element: ::before, ::placeholder, Weight:0-0-1

【Exceptions】

  • The wildcards *and pseudo-classes :where()and their parameters do not contribute any weight, i.e.0-0-0
  • The combinators +, >, ~, " " , and do not contribute weight ||by themselves .
  • Pseudo-classes :not(), :is()and do not contribute weights :has()themselves , but their parameters compute weights.
  • Inherited style weights are zero.

[Exercise] Calculate the weight of the following rules:

[type="password"]             /* 0-1-0 */
input:focus                   /* ? */
:root #myApp input:required   /* ? */
h2:has(~ h2)                  /* ? */

【inline style】

An inline style has no selector, and its weight can be regarded as: 1-0-0-0, or it has a higher priority than any style sheet. The only way to override an inline stylesheet is to use !important.

CSS style inheritance

Some attribute values ​​of child elements can be inherited from parent elements, and using this feature can reduce a lot of repetitive code.

inherited properties

  1. font family attribute
  • font-family: font family
  • font-weight: the thickness of the font
  • font-size: the size of the font
  • font-style: the style of the font
  1. Text Series Properties
  • text-indent: text indentation
  • text-align: horizontal alignment of the text
  • line-height: row height
  • word-spacing: the spacing between words
  • letter-spacing: spacing between Chinese or letters
  • text-transform: Control text case (that is, uppercase, lowercase, capitalize these three)
  • color: text color
  1. element visibility
  • visibility: control element display hide
  1. List Layout Properties
  • list-style: list style, including list-style-type, list-style-image, etc.
  1. cursor properties
  • cursor: what shape the cursor is displayed in

[Exception] aThe font size and color of the label are not inherited. This is due to the existence of the browser style (user agent style sheet), which can be added to the initialization style sheet:

a{
    
    
    font-size: inherit;
    color: inherit;
}

You can say goodbye to the default style.

[Exception] The width of block-level elements in normal document flow is inherited. Some students like to add elements width: 100%;. In fact, there is no need to do so in many cases. Some students center the floating or positioning box and find that it cannot be centered. This is because the unflowing box does not inherit the width of the parent element, and its width is determined by the content. Open up.

【Exercise】What is the color of Q123?

<style>
    .main{
      
      
        color:blue
    }
    span{
      
      
        color:green
    }
</style>
<div style="color:red !important" class="main">
    <span>123</span>
</div>

non-inherited properties

Although it is enough to remember the attributes with inheritance, you need to refer to the attributes without inheritance for reference, so as not to have a fluke mentality. Note: The width of the box model is a special case.

  1. display : specifies the type of box the element should generate
  2. Special text properties :
  • vertical-align: vertical text alignment
  • text-decoration: specifies the decoration to add to the text
  • text-shadow: text shadow effect
  • white-space: processing of blank characters
  • unicode-bidi: set the direction of the text
  1. Box model attributes : width, height, margin, border, padding, outline, min-width, min-height, max-width, max-height, overflow, clip,
  2. 背景属性:background、background-color、background-image、background-repeat、background-position、background-attachment
  3. Floating and positioning attributes : float, clear, position, top, right, bottom, left, z-index
  4. Generate content attributes : content, counter-reset, counter-increment
  5. Page style attributes : size, page-break-before, page-break-after
  6. Sound style attributes : pause-before, pause-after, pause, cue-before, cue-after, cue, play-during

CSS variables

I don’t know if you have heard of CSS variables in front of the screen. When checking the source code of some websites, I accidentally discovered the good thing of CSS variables:

insert image description here

CSS variables can be used to easily adjust the style of the webpage, especially combined with JavaScript, the style can be adjusted more elegantly, and the CSS variable can be used to easily realize the function of changing the skin of the webpage.

Understanding CSS Variables 4

statement :--var-name: var-value;

read :var(--var-name, [fallback-value])

type :

  • Normal: can only be used as attribute value and not as attribute name
  • Numerical values: use calc()with numeric unitsvar(--width) * 10px

Scope : Valid under the current element block scope and its child element block scopes.

JavaScript API

There are mainly three APIs for manipulating CSS variables in JavaScript , which look simple and easy to remember, as follows:

  • Read variables:elem.style.getPropertyValue()
  • Set variables:elem.style.setProperty()
  • Delete variable:elem.style.removeProperty()

reference article

♥ I'm a front-end engineer: your sweetheart Sen. Thank you very much for your likes and attention, and welcome everyone to participate in discussions or collaborations.

★ This article is open source , using the CC BY-SA 4.0 protocol , please indicate the source for reprinting: Self-cultivation of front-end engineers . GitHub.com@xiayulu.

★ For creative cooperation or recruitment information, please send a private message or email: [email protected], specifying the subject: creative cooperation or recruitment of front-end engineers .
tribute_selectors).


  1. MDN. Attribute selectors. ↩︎

  2. MDN. CSS selectors. ↩︎

  3. MDN. Specificity. ↩︎

  4. JowayYoung. Use CSS variables to make your CSS more exciting . Rare earth nuggets. ↩︎

Guess you like

Origin blog.csdn.net/hongshuteng/article/details/127563357