frontend 學習筆記 - more on css
Browser default style
每個瀏覽器會有自己的 default style,所以網路上有開源的 .css 讓開發者們用,可以 undo browser default style 然後根據自己的規則在不同的瀏覽器上顯示一樣的東西
常用的有
這邊 可以看到瀏覽器的 default style
Absolute/Relative Unit
Absolute
像是 px 這種直接給定幾個 pixel 的Relative
- em/rem
- em: 看元素的 font-size,如果元素的 font-size 是 10px,那 2em = 10px * 2 = 20px
- rem(recommended): 看
:root
或html
的 font-size
- viewport Unit
- vh: 1vh = 1% viewport height
- vw: 1vw = 1% viewport width
- viewport unit 可以做的事
- em/rem
font
- online font library
使用
1 2 3
<link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
或者
1 2
/* style.css */ @import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
text styles
如果只是想讓字變斜體用
font-style
,文字要斜體又加強重點的話用<em>
控制文字橫間距用
letter-spacing: .5em
,行間距用letter-height: 1.5
text-transform
可以變內容全部變大/小寫text-shadow
可以幫文字加陰影ellipsis
可以讓超過範圍的文字隱藏,搭配使用如下1 2 3 4 5
.overflowing { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
其中
overflow
也可以設定成visible
、scroll
之類的
advanced selectors
Parent and Sibling Combinators
>
: child combinator+
: adjacent sibling combinator~
: general sibling combinator
例子
|
|
|
|
pseudo class/element
pseudo class 就是讓特定的 html tag 不用寫 class 來加上 css,為什麼不寫 class 是因為可能想指定的是文章第一段,那文章一直增加 html 就要一直改
常用的 pseudo class 有
:root
:first-child
、:last-child
、:only-child
、:empty
(沒小孩)、:nth-child
用法:invalid
:hover
、:visited
、:focus
、:link
pseudo element 也是類似的意思,只是它會指的東西是 tag 裡的內容,例如段落的第一行之類的,也可以同時跟 pseudo class 並用
常用的 pseudo element:
::before
、::after
: 可以在裡面設定content
顯示在元素的前後,或者content
為空字串放 block 之類的,可以參考 這個例子::marker
可以調整<li>
的 style::first-letter
、::first-line
::selection
: 可以讓使用者在用滑鼠選文字的時候出現想要的 css style
attribute selectors
[attribute]
: 選所有有這個 attribute 的selector[attribute]
: 選這些 selector 有 這個 attribute 的[attribute="value"]
: 選有這個 attribute 且 value 是特定的
例子
|
|
搭配 regex 使用的話
[attribute^="value"]
: value 前綴有 “value” 的[attribute$="value"]
: value 後綴有 “value” 的[attribute*="value"]
: value 中任何地方有出現 “value” 的
Positioning
- static: 會被放在預設的位置
- relative: 跟 static 差不多但是可以定義 top, bottom, left, right
- absolute: 透過定義 top, bottom, left, right 放在螢幕上的固定位置,適用的 case 有
- modals
- image with a caption on it
- icons on top of other elements
- fixed: 會直接固定在螢幕上,不管怎麼滑動都會在那裡 ex. 導覽列、聊天按鍵
- sticky: 還沒滑到之前跟一般元素一樣,滑經過後會變成 fixed
CSS functions
calc()
: 可以透過 css variable 去算各個區塊的大小 例子min()
、max()
: 選最小/大的 例子clamp()
: 要給三個參數,smallest value, ideal value, largest value- 其他
custom properties
- CSS variable declaration:
--
為開頭,用-
來分開單字 ex.--color-error-text
- 跟 js 一樣有 scope 的概念,可以繼承,如果是全部都可以用的話可以定義在
:root
- 實際應用