一些CSS技巧的收集,能夠幫助你提升專業(yè)水平。
1. 使用 :not() 為導(dǎo)航添加/取消邊框
很多人會這樣給導(dǎo)航添加邊框,然后給最后一個(gè)取消掉:
/* add border */
.nav li {
border-right: 1px solid #666;
}
/* remove border */
.nav li:last-child {
border-right: none;
}
其實(shí),用CSS的 :not() 可以簡化為下面的代碼:
.nav li:not(:last-child) {
border-right: 1px solid #666;
}
當(dāng)然,你也可以使用 .nav li + li 甚至 .nav li:first-child ~ li,但是使用 :not() 可以使意圖更加明確。
2. 給 body 添加 line-height 屬性
你不需要為 <p>、<h*> 分別添加 line-height 屬性,相反的,只需要添加到 body 上即可:
body {
line-height: 1;
}
這樣,文本元素就可以很容易的從 body 繼承該屬性。
3. 垂直居中
這并不是什么魔法,你可以垂直居中任何元素:
html, body {
height: 100%;
margin: 0;
}
body {
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
display: -webkit-flex;
display: flex;
}
還需要其他的?水平居中、垂直居中,在任何時(shí)間、任何地方?可以看看CSS-Tricks的這篇文章。
注意:flexbox 在 IE11 下存在一些bug。
4. 使用逗號分割列表
使列表看起來像是用逗號分割的:
ul > li:not(:last-child)::after {
content: ",";
}
通過 :not() 偽類去掉最后一個(gè)元素后面的逗號。
5. 使用負(fù)的 nth-child 選取元素
使用負(fù)的 nth-child 在 1 到 n 之間選擇元素:
li {
display: none;
}
/* 選擇第1到3個(gè)元素并顯示它們 */
li:nth-child(-n+3) {
display: block;
}
當(dāng)然,如果你了解 :not() 的話,還可以這么做:
li:not(:nth-child(-n+3)) {
display: none;
}
是不是非常簡單?
6. 使用 SVG 作 icon 圖標(biāo)
沒什么理由不使用 SVG 作 icon 圖標(biāo):
.logo {
background: url("logo.svg");
}
SVG 對于任何分辨率的縮放效果都很好,并且支持 IE9+所有瀏覽器,所以,放棄使用 .png、.jpg、.gif文件吧。
注:以下代碼對于使用輔助設(shè)備上網(wǎng)的用戶可以提升可訪問性:
.no-svg .icon-only:after {
content: attr(aria-label);
}
7. 文本展示優(yōu)化
有時(shí)候字體并不是對于所有設(shè)備都顯示為最佳效果,所以使用瀏覽器來幫忙吧:
html {
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
}
8. 使用 max-height 實(shí)現(xiàn)純CSS幻燈片
使用 max-height 與超出隱藏實(shí)現(xiàn)純CSS的幻燈片:
.slider ul {
max-height: 0;
overlow: hidden;
}
.slider:hover ul {
max-height: 1000px;
transition: .3s ease; /* animate to max-height */
}
9. 繼承 box-sizing
讓 box-sizing 繼承自 html :
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
這使得在插件或者其他組件中修改 box-sizing 屬性變得更加容易。
10. 設(shè)置表格相同寬度
.calendar {
table-layout: fixed;
}
11. 使用 Flexbox 來避免 Margin Hacks
在做多列布局的時(shí)候,可以通過 Flexbox 的 space-between 屬性來避免nth-、first-、 last-child 等 hacks:
.list {
display: flex;
justify-content: space-between;
}
.list .person {
flex-basis: 23%;
}
這樣,列之間的空白就會被均勻的填滿。
13. 對空鏈接使用屬性選擇器
當(dāng) <a> 中沒有文本而 href 不為空的時(shí)候,顯示其鏈接:
a[href^="http"]:empty::before {
content: attr(href);
}
瀏覽器支持
以上技巧支持大部分現(xiàn)代瀏覽器,如:Chrome、Firefox、Safari、Edge以及IE11。
via:github,由 Specs 翻譯整理,發(fā)布在 Coder資源網(wǎng),轉(zhuǎn)載請注明來源。
哈爾濱品用軟件有限公司致力于為哈爾濱的中小企業(yè)制作大氣、美觀的優(yōu)秀網(wǎng)站,并且能夠搭建符合百度排名規(guī)范的網(wǎng)站基底,使您的網(wǎng)站無需額外費(fèi)用,即可穩(wěn)步提升排名至首頁。歡迎體驗(yàn)最佳的哈爾濱網(wǎng)站建設(shè)。
