實(shí)用的CSS高級(jí)技巧 Part1

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;
}
Screen Shot 2017-04-03 at 12.15.04 PM.png

如果想讓空的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三部分。

Screen Shot 2017-04-03 at 1.19.38 PM.png
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)圖展示效果:


responsivecontent.gif

再加上一些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。

alwaycenter.gif

用這樣的方法很簡(jiǎn)單就能寫出一個(gè)整頁page上下滑的網(wǎng)頁效果:

ezgif.com-resize.gif

沒有用到任何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è)贊吧(? ??_??)?!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 問答題47 /72 常見瀏覽器兼容性問題與解決方案? 參考答案 (1)瀏覽器兼容問題一:不同瀏覽器的標(biāo)簽?zāi)J(rèn)的外補(bǔ)...
    _Yfling閱讀 13,786評(píng)論 1 92
  • 本文轉(zhuǎn)載自:眾成翻譯譯者:為之漫筆鏈接:http://www.zcfy.cc/article/239原文:http...
    極樂君閱讀 7,397評(píng)論 1 62
  • 1.class 和 id 的使用場(chǎng)景? 類選擇器允許以一種獨(dú)立于文檔元素的方式來指定樣式。該選擇器可以單獨(dú)使用,也...
    草鞋弟閱讀 2,446評(píng)論 0 1
  • #我的第一個(gè)文檔#
    魔芋Brace閱讀 382評(píng)論 0 1
  • 上了大學(xué),有這樣一件事很尷尬——原來你以前沒有男(女)朋友不是因?yàn)閷W(xué)校禁止早戀。看過很多關(guān)于上大學(xué)的雞湯文,認(rèn)為大...
    2d2d68835291閱讀 464評(píng)論 2 1