幾個CSS的黑科技
原文出處: JellyBool(@JellyBool)
昨天由于某些原因沒有寫博客,之前說好的每天一篇的,這篇是為了補昨天的了。然后我就要當一次標題黨了。這里的黑科技其實就是一些CSS中不怎么為人所知但在解決某些問題的時候很溜的屬性。
border-radius
很多開發者估計都沒有正確認識這個border-radius,因為基本上很多人都是這么用的:
.box {
border-radius: 4px;
}|
1
2
3
|
.box {
border-radius: 4px;
}
|
稍微高端一點的是這樣的:
.box {
border-radius: 4px 6px 6px 4px;
}|
1
2
3
|
.box {
border-radius: 4px 6px 6px 4px;
}
|
然而,終極黑科技是這樣用的:
.box {
border-radius: 5px 5px 3px 2px / 5px 5px 1px 3px;
}|
1
2
3
|
.box {
border-radius: 5px 5px 3px 2px / 5px 5px 1px 3px;
}
|
對,它可以賦8個值,沒見過?不著急,具體的解釋是這樣的:
斜線前面的影響的是水平方向,斜線后面影響的是垂直方向,各個數字就分別代表四個不一樣的方向。
|
1
|
斜線前面的影響的是水平方向,斜線后面影響的是垂直方向,各個數字就分別代表四個不一樣的方向。
|
outline-offset
相信很多開發者在寫CSS的時候對下面的語句會很熟悉:
input {
outline : none;
}
input:focus {
outline : none;
}|
1
2
3
4
5
6
7
|
input {
outline : none;
}
input:focus {
outline : none;
}
|
這就是將input輸入框去掉默認的藍線框的方法。其實,這里還有說一個就是,CSS中還有一個outline-offset屬性,在這個屬性中,你可以設置默認線框的距離;像這樣
input {
outline-offset: 4px ;
}|
1
2
3
|
input {
outline-offset: 4px ;
}
|
調節該屬性值的大小你就可以看到outline的距離變化了。
類的聲明
對于下面的類的聲明,可能大家都很熟悉:
.col-8 {
}|
1
2
3
|
.col-8 {
}
|
這當然沒什么,但是如果你這樣寫呢:
.? {
color: hotpink;
}
.★ {
color: yellow;
}|
1
2
3
4
5
6
7
|
.? {
color: hotpink;
}
.★ {
color: yellow;
}
|
嗯,看起來怎么樣,你是可以這么用的:
<div class="? ★"></div>
|
1
|
<div class="? ★"></div>
|
只要是Unicode的,你都可以這么來聲明你的類。
選中連續的幾個元素
ol li:nth-child(n+7):nth-child(-n+14) {
background: lightpink;
}
/** Or Safari Way **/
ol li:nth-child(-n+14):nth-child(n+7) {
background: lightpink;
}|
1
2
3
4
5
6
7
|
ol li:nth-child(n+7):nth-child(-n+14) {
background: lightpink;
}
/** Or Safari Way **/
ol li:nth-child(-n+14):nth-child(n+7) {
background: lightpink;
}
|
上面的這種寫法其實就可以達到選中ol下面的第七到第十四個li元素。
偽類設置單標簽
html中有幾個常見的單標簽:<br> ,<hr>等。具體可以查看這里:
http://www.w3.org/TR/html5/syntax.html#void-elements
下面的示例是實現對<hr>的修飾。
hr:before {
content: "??";
}
hr:after {
content: " This is an <hr> element";
}|
1
2
3
4
5
6
7
|
hr:before {
content: "??";
}
hr:after {
content: " This is an <hr> element";
}
|
沒錯,關鍵就是使用 :before 和 :after 這兩個偽類。在這里,順便說一點就是,其實你還可以用這兩個偽類來修飾 <meta> 和 <link> ,不過這個前提是,你把這兩個的 display 屬性設置為:
display: block
|
1
|
display: block
|
屬性區分大小寫
假如我們在寫html的時候有類似下面的代碼:
<div class="box"></div> <input type="email">
|
1
2
|
<div class="box"></div>
<input type="email">
|
然后我們用屬性選擇器進行CSS修飾:
div[class="box"] {
color: blue;
}
input[type="email"] {
border: solid 1px red;
}|
1
2
3
4
5
6
7
|
div[class="box"] {
color: blue;
}
input[type="email"] {
border: solid 1px red;
}
|
這樣的聲明方式毫無疑問地就會生效。然而,如果我們聲明成下面這個樣子,結果會是怎么樣的呢:
div[class="BOX"] {
color: blue;
}
input[type="EMAIL"] {
border: solid 1px red;
}|
1
2
3
4
5
6
7
|
div[class="BOX"] {
color: blue;
}
input[type="EMAIL"] {
border: solid 1px red;
}
|
這變成了大寫之后,第一個 class="BOX" 并不會影響到 <div class="box"></div> ,而第二個 type="EMAIL" 還是會正常修飾 <input type="email"> 。所以在使用屬性選擇器的時候,注意大小寫問題。
目前就只覺得這些CSS黑科技需要提醒自己一下,有可以補充。
Happy Hacking