css常用高級技巧

使用:not()在菜單上添加/取消邊框

css常用高級技巧


很多人會這樣給導航添加邊框,然後給最後一個取消掉:

/* add border */
.nav li {
border-right: 1px solid #666;
}
/* remove border */
.nav li:last-child {
border-right: none;
}

其實,用CSS3的:not()可以簡化為下面的代碼:

.nav li:not(:last-child) {
border-right: 1px solid #666;
}

當然,你也可以使用.nav li + li甚至.nav li:first-child ~ li,但是使用:not()可以使意圖更加明確

所有主流瀏覽器均支持:not選擇器,除了IE8及更早的版本

給body添加line-height屬性


你不需要為

分別添加line-height屬性,相反的,只需要添加到body上即可:

body {
line-height: 1;
}

這樣,文本元素就可以很容易的從body繼承該屬性

垂直居中


可以垂直居中任何元素:

html, body {
height: 100%;
margin: 0;
}
body {
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
display: -webkit-flex;
display: flex;
}

注:flexbox在IE11下存在一些bug

使用逗號分割列表


使列表看起來像是用逗號分割的:

ul > li:not(:last-child)::after {
content: ",";
}

通過:not()偽類去掉最後一個元素後面的逗號

使用負的nth-child選取元素


使用負的nth-child在1到n之間選擇元素:

li {
display: none;
}
/* 選擇第1到3個元素並顯示它們 */
li:nth-child(-n+3) {
display: block;
}

當然,如果你瞭解:not()的話,還可以這麼做:

li:not(:nth-child(-n+3)) {
display: none;
}

使用SVG作icon圖標


沒什麼理由不使用SVG作icon圖標:

.logo {
background: url("logo.svg");
}

SVG對於任何分辨率的縮放效果都很好,並且支持 IE9+所有瀏覽器,所以,放棄使用png、jpg、gif文件吧

注:以下代碼對於使用輔助設備上網的用戶可以提升可訪問性:

.no-svg .icon-only:after {
content: attr(aria-label);
}

優化顯示文本

css常用高級技巧


有時,字體並不能在所有設備上都達到最佳的顯示,所以可以讓設備瀏覽器來幫助你:

html {
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
}

注:請負責任地使用optimizeLegibility。此外IE/Edge不支持text-rendering

使用max-height實現純CSS幻燈片


使用max-height與超出隱藏實現純CSS的幻燈片:

.slider ul {
max-height: 0;
overlow: hidden;
}
.slider:hover ul {
max-height: 1000px;
transition: .3s ease; /* animate to max-height */
}

繼承box-sizing


讓box-sizing繼承自html:

html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}

這使得在插件或者其他組件中修改box-sizing屬性變得更加容易

設置表格相同寬度


.calendar {
table-layout: fixed;
}

使用Flexbox來避免Margin Hacks


在做多列布局的時候,可以通過Flexbox的space-between屬性來避免nth-、first-、 last-child等hacks:

.list {
display: flex;
justify-content: space-between;
}
.list .person {
flex-basis: 23%;
}

這樣,列之間的空白就會被均勻的填滿

對空鏈接使用屬性選擇器


a[href^="http"]:empty::before {
content: attr(href);
}

文本溢出省略的處理方法

單行文本溢出

.inline{
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}

多行文本溢出

.foo{
display: -webkit-box!important;
overflow: hidden;
text-overflow: ellipsis;
word-break: break-all;
-webkit-box-orient: vertical;/*方向*/
-webkit-line-clamp:4;/*顯示多少行文本*/
}


分享到:


相關文章: