理解CSS | 青训营笔记

111 阅读1分钟

这是我参与「第四届青训营」笔记创作活动的的第2天

选择器 Selecter

通配选择器

<h1>This is heading</h1>
<p>This is some paragraph.</p>

<style>
    * {
    color:red;
    font-size:20px;
    }
</style>

标签选择器

<h1>This is heading</h1>
<p>This is some paragraph.</p>

<style>
    h1 {
        color: orange;
    }
    p {
        color: gray;
        font-size:20px;
    }
</style>

id选择器

<h1 id="logo">
    <img
       src="https://assets.codepen.io/59477/h5-logo.svg" alt="HTML5 logo" width="48"/>
    HTML5 文档
</h1>
    
<style>
    #Logo {
        font-size60px;
        font-weight: 200;
    }
</style>

类选择器

<h2>Todo List</h2>
<ul>
    <li class="done">Learn HTML</li>
    <li class="done">Learn CSS</li>
    <li>Learn JavaScript</li>
</ul>

<style>
    .done {
        color: gray;
        text-decoration:Line-through;
</style>

属性选择器

<Label>用户名:</label>
<input value="zhao" disabled />
<label>密码:</label>
<input value="123456" type="password"/>

<style>
    [disabled] {
        background: #eee;
        color: #999;
    }
    input[type="password"] {
        border-color: red;
        color: red;
    }
</style>

伪类(pseudo-classes)

<style>
    a:link{   }
    a:visited {  }
    a:active {  }
    :focus{   }
    li:first-child{	  }
    li:last-child{	 }
</style>

image-20220725222303140

选择器的特异度

image-20220725223846380

  • id > . > E

继承

某些属性回自动继承其父元素的计算值,除非显式指定一个值

文字属性(color等)一般都可继承,和模型相关的属性(p的width等)一般不可继承

显式继承

inherit

让一个不可继承的属性变成可继承

<style>
    * {
        box-sizing: inherit;
    }
    html {
        boxing-sizing: border-box;
    }
    .some-widget {
        box-sizing: content-box;
    }
</style>

如果从元素父集一层一层往上找没找到 => 初始值

初始值

  • CSS中,每个属性都有一个初始值
    • background-color 的初始值为 transparent
    • margin-left 的初始值为 0
  • 可以使用 initial 关键字显式重置为初始值
    • background-color: initial

CSS求值过程

CSS/取值过程 (cdpn.io)

布局(Layout)

image-20220725225721636

  • 确定内容的大小和位置的算法
  • 依据元素、容器、兄弟节点和内容等信息来计算

布局相关技术

image-20220725225642665

image-20220725225748142

Flex布局:一维

Grid布局:二维

image-20220725231138968

绝对定位

position属性

  • static 默认值,非定位元素
  • relative 相对自身原本位置偏移,不脱离文栏流
  • absolute 绝对定位,相对非 static 祖先元素定位
  • fixed 相对于视口绝对定位