1 偽類選擇器
1.1 :empty
選擇內(nèi)容為空的元素。:not(:empty)
不為空的元素。
舉個(gè)栗子:
<body>
<div class="Alert">
<p>Success! Your profile has been updated.</p>
</div>
<div class="Alert">
</div>
</body>
.Alert {
border: 3px solid darkgreen;
margin: 1em;
padding: 1em;
background-color: seagreen;
color: white;
border-radius: 4px;
}
如果想讓空的alert隱藏可以:
.Alert:empty {
display: none;
}
但更簡(jiǎn)單的方法是:
.Alert:not(:empty) {
border: 3px solid darkgreen;
margin: 1em;
padding: 1em;
background-color: seagreen;
color: white;
border-radius: 4px;
}
這樣的嵌套式使用偽類選擇器的例子還有很多
比如:not(:last-child)
,:not(:first-child)
。
1.2 選擇同類元素中的第一個(gè)/第n個(gè)/唯一一個(gè)等。也非常實(shí)用。
first-of-type
last-of-type
only-of-type
nth-of-type(odd)
nth-of-type(even)
nth-of-type(3)
nth-of-type(4n+3)
2.calc()實(shí)現(xiàn)響應(yīng)式設(shè)計(jì)
比如一個(gè)這樣結(jié)構(gòu)的網(wǎng)頁,包含nav,main,aside三部分。
nav {
position: fixed;
top: 0;
left: 0;
width: 5rem;
height: 100%;
}
aside {
position: fixed;
top: 0;
right: 0;
height: 100%;
width: 20rem;
}
當(dāng)屏幕尺寸變化的時(shí)候,希望保持當(dāng)前的布局,讓中間的content隨之變化,只需要一行css就能實(shí)現(xiàn)了。
main {
margin-left: 5rem;
width: calc(100% - 25rem);
}
如下圖gif動(dòng)圖展示效果:
再加上一些media query,就是一個(gè)完整的針對(duì)移動(dòng)設(shè)備和pc的響應(yīng)式css。
3.用vh,vw規(guī)定元素大小
經(jīng)常被使用到的單位是px,em,rem
你有沒有用過更簡(jiǎn)單的vh,vw呢,這兩個(gè)單位是相對(duì)于當(dāng)前viewport的百分比??梢院芎?jiǎn)單的控制元素在viewport中的相對(duì)位置:
.Box {
height: 40vh;
width: 50vw;
margin: 30vh 25vw;
}
只需要這一點(diǎn)點(diǎn)css就能讓box這個(gè)元素不論viewport size如何變化都保持永遠(yuǎn)居中。因?yàn)?code>height+marginTop+ marginBottom = 100vh, width+marginLeft+marginRight = 100vw
。
用這樣的方法很簡(jiǎn)單就能寫出一個(gè)整頁page上下滑的網(wǎng)頁效果:
沒有用到任何js,非常簡(jiǎn)單的css,如下:
section {
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
background-size: cover;
background-repeat: no-repeat;
background-attachment: fixed;
}
如果覺得有用,請(qǐng)給我點(diǎn)個(gè)贊吧(? ??_??)?!