22個CSS黑魔法

ido321發表於2016-01-26

Hey there! Today we are going to talk about some useful tricks in CSS. Let's begin with…

在這篇文章中我們會談論一些有用的 CSS 技巧…

Blend Modes

混合模式

Not so far Firefox and Safari started to support blend modes right as Photoshop does. It also works in Chrome and Opera but with flags. See an example:

到目前為止,Firefox 和 Safari 已經能和 Photoshop 一樣支援混合模式了,Chrome 和 Opera 也通過帶私有標誌(-webkit- & -o-)支援,看一個示例:

blend modes

You can create different styles. Here's a code of what is going above:

你可以建立不同的混合風格。上述示例的程式碼如下:

.blend {
    background: #fff;
}
.blend img {
    mix-blend-mode: darken; 
}

來試試混合模式和過濾

Gradient Borders

邊框漸變

Novadays you can use gradients even in borders.

在邊框中也能使用漸變效果了。

gradient borders

It is rather simple to use, just need to set pseudo-elements with lower z-index:

邊框漸變的效果實現很簡單,僅僅只需為偽元素設定更低的 z-index :

.box {
  margin: 80px 30px;
  width: 200px;
  height: 200px;
  position: relative;
  background: #fff;
  float: left;
}
.box:before {
      content: '';
      z-index: -1;
      position: absolute;
      width: 220px;
      height: 220px;
      top: -10px;
      left: -10px;
      background-image: linear-gradient(90deg, yellow, gold);
}

All examples you can find here. Also there is approach with background-clip and background-origin. Someday in the bright future border-image property will be supported by all browsers and solution for this will look as follow:

這裡能找到更多示例,另一種方法是通過 background-clip 和 background-origin 來實現。在未來的某一天,border-image 會被所有瀏覽器支援,其提供的邊框漸變方式可能如下:

.box {
    border-image: linear-gradient(to bottom, #000000 0%, #FFFFFF 100%); 
    border-image-slice: 1; /* set internal offset */
}

Transition for z-index

z-index 過渡

You may didn't know but z-index supports transitions too! It doesn't change it's value on each step so you think that it doesn't have a transition. But it does!

你可能不知道 z-index 也支援過渡效果!它沒有在每一步改變它的值,所以你認為它沒有過渡效果,但實際上是有的!

transition for z-index

這有一個很棒的示例

currentColor

We can use it to detect the current color so we don't have to define it lots of times.

我們可以使用 currentColor 來檢測元素當前使用的顏色,因而不需要定義 color 很多次。

It can be useful when working with SVG icons which change their color depending on their parents. Usually we do it as follows:

結合 SVG 圖示使用時,currentColor 是很有用的,因為圖示顏色的改變取決於它們的父元素。通常我們是這麼做的:

.button {
  color: black;
}
.button:hover {
  color: red;
}
.button:active {
  color: green;
}

.button svg {
  fill: black;
}
.button:hover svg {
  fill: red;
}
.button:active svg {
  fill: green;
}

使用 currentColor 之後:

svg {  
  fill: currentColor;
}

.button {
  color: black;
  border: 1px solid currentColor;
}
.button:hover {
  color: red;
}
.button:active {
  color: green;
}

另一種方式是用於偽元素:

a {  
  color: #000;
}
a:hover {  
  color: #333;
}
a:active {  
  color: #666;
}

a:after,  
a:hover:after,  
a:active:after {  
  background: currentColor;
  ...
}

Object Fit

物件適配

Do you remember this moment when you wanted to set background-size for image because it will solve a lot of problems? Now you can use object-fit which is supported by webkit and will be added to Firefox soon.

你還記得通過設定圖片的 background-size 屬性可以解決很多問題的時刻嗎?現在你可以使用 object-fit 了,它已經被 webkit 核心的瀏覽器支援,不久 Firefox 也會支援。

.image__contain {
  object-fit: contain; 
} 
.image__fill {
  object-fit: fill; 
}
.image__cover {
  object-fit: cover; 
}
.image__scale-down {
  object-fit: scale-down;
}

object fit

示例

Checkbox and Radio Buttons Styles

核取方塊和單選按鈕的樣式

讓我們不使用圖片來改變核取方塊的樣式:

 <input type="checkbox" id="check" name="check" />
 <label for="check">Checkbox</label>
input[type=checkbox] {display: none;}

input[type=checkbox] + label:before {  
    content: "";
    border: 1px solid #000;
    font-size: 11px;    
    line-height: 10px;
    margin: 0 5px 0 0;
    height: 10px;
    width: 10px;
    text-align: center;
    vertical-align: middle;
}

input[type=checkbox]:checked + label:before {  
    content: "\2713";
}

checkbox

As you can see, it works with pseudo-elements and pseudo-selector :checked (IE9+). In the code above we hide original checkbox and show ours instead. When checked, we show a Unicode character using the content.

正如你看到的,需要結合使用偽元素和偽類選擇器 :checked(IE9+)。在上面的程式碼中,隱藏了原始的核取方塊,顯示它的替代元素。當核取方塊被選中時,通過使用 content 屬性顯示一個 Unicode 字元。

Note that the Unicode character in CSS differs from that in HTML. In CSS the number is specified in hexadecimal notation with trailing slash at the beginning, while in HTML it's decimal and will look like ✓.

需要注意的是 Unicode 字元在 CSS 和 HTML 中的表示是不同的。在 CSS 中,數字是被指定為以反斜槓開頭的十六進位制方式,而在 HTML 中是形如 ✓ 的十進位制方式。

給核取方塊新增動畫效果:

input[type=checkbox] + label:before {  
    content: "\2713";
    color: transparent;
    transition: color ease .3s;
}
input[type=checkbox]:checked + label:before {  
    color: #000;

給單選按鈕新增動畫效果:

input[type=radio] + label:before {  
    content: "\26AB";
    border: 1px solid #000;
    border-radius: 50%;
    font-size: 0;    
    transition: font-size ease .3s;
}
input[type=radio]:checked + label:before {  
    font-size: 10px;   

checkbox & radio

這裡 有完整的 Unicode 列表和示例 程式碼。

譯者補充:

核取方塊的 CSS 魔法

利用checkbox實現 jQuery 的6中基本動畫效果

Counters in CSS

CSS 計數器

並不是所有人都知道 CSS 可以用於計數:

<ol class="list">  
    <li>a</li>
    <li>b</li>
    <li>c</li>
</ol>  
.list {
    counter-reset: i; //reset conunter
}
.list > li {
    counter-increment: i; //counter ID
}
.list li:after {
    content: "[" counter(i) "]"; //print the result
}

We define a random ID in counter-reset property and it's first value (0 by default). You can set another number in counter-increment. It will define the step of your counter.

For example counter-increment: i 2 will displays only even numbers.

在 counter-reset 屬性中,定義了一個隨機 ID,其預設值是0。你可以在 counter-increment 屬性中定義另外一個數字,作為計數的步長。

例如:counter-increment: i 2 將值顯示偶數。

譯者補充:詳解content屬性

Advanced CSS Counters

CSS 計數器進階

利用 CSS 計數器,能統計被使用者選擇的核取方塊個數:

<div class="languages">  
  <input id="c" type="checkbox"><label for="c">C</label>
  <input id="C++" type="checkbox"><label for="C++">C++</label>
  <input id="C#" type="checkbox"><label for="C#">C#</label>
  <input id="Java" type="checkbox"><label for="Java">Java</label>
  <input id="JavaScript" type="checkbox"><label for="JavaScript">JavaScript</label>
  <input id="PHP" type="checkbox"><label for="PHP">PHP</label>
  <input id="Python" type="checkbox"><label for="Python">Python</label>
  <input id="Ruby" type="checkbox"><label for="Ruby">Ruby</label>
</div>  
<p class="total">  
  Total selected:
</p>  
.languages {
  counter-reset: characters;
}
input:checked {  
  counter-increment: characters;
}
.total:after {
  content: counter(characters);
} 

這個示例中,我們會增加 input:checked 的數量並列印出來。

input:checked

你還能建立一個小型計算器:

<div class="numbers">  
  <input id="one" type="checkbox"><label for="one">1</label>
  <input id="two" type="checkbox"><label for="two">2</label>
  <input id="three" type="checkbox"><label for="three">3</label>
  <input id="four" type="checkbox"><label for="four">4</label>
  <input id="five" type="checkbox"><label for="five">5</label>
  <input id="one-hundred" type="checkbox"><label for="one-hundred">100</label>
</div>  
<p class="sum">  
  Sum 
</p> 
.numbers {
  counter-reset: sum;
}

#one:checked { counter-increment: sum 1; }
#two:checked { counter-increment: sum 2; }
#three:checked { counter-increment: sum 3; }
#four:checked { counter-increment: sum 4; }
#five:checked { counter-increment: sum 5; }
#one-hundred:checked { counter-increment: sum 100; }

.sum::after {
  content: '= ' counter(sum);
} 

原理和上面的示例是一樣的,線上demo相關文章

counter

Menu Icon Without Images

沒有圖片的選單圖示

還記得你經常使用的漢堡包圖示嗎?

hamburger

至少有三種關於怎麼繪出這種圖示的方法:

1、Shadows

 .shadow-icon {
   position: relative;
   }
   .shadow-icon:after {
     content: "";
     position: absolute;
     left: 0;
     top: -50px;
     height: 100%;
     width: 100%;
     box-shadow: 0 5px 0 #000, 0 15px 0 #fff, 0 25px 0 #000, 0 35px 0 #fff, 0 45px 0 #000;
     }

2、Gradient

.gradient-icon {
    background: linear-gradient(to bottom, #000 0%, #000 20%, transparent 20%, transparent 40%, #000 40%, #000 60%, transparent 60%, transparent 80%, #000 80%, #000 100%);
}

3、UTF-8

You can just paste this standard symbol: ☰ (Unicode: U+2630, HTML: &#9776;). You can adjust it's color or size only so it's not as flexible as other methods.

只需要貼上圖示的標準符號:☰(Unicode: U+2630,HTML: ☰),你可以調整它的顏色或大小,但它不如其它方法靈活。

可以看示例

此外,你也可以使用 SVG,icon font 或 borders 集合偽元素的方式來實現。

@Supports

There's a new expression in CSS called supports. As you can see, it can inspect whether browser supports needed option. Not all of browser support it, but you still can use it for simple checks:

CSS 中有一個被稱為 supports 的新的表示式。正如你看到的,它能檢測瀏覽器是否支援某屬性。雖然並不是所有瀏覽器支援 @support 表示式,但你仍然可以使用它作一些簡單的檢測:

@supports (display: flex) {
    div { display: flex; }
}

/*You can check prefixes*/
@supports (display: -webkit-flex) or (display: -moz-flex) or (display: flex) {
    section {
        display: -webkit-flex;
        display: -moz-flex;
        display: flex;
        float: none;
    }
}

譯者補充:An Introduction to CSS’s @supports Rule

visibility: visible

如果你將一個 visibility:visible 的塊元素放在另一個 visibility:hidden 的元素中,會產生什麼效果呢?

.hidden {
  visibility: hidden;
}
.hidden .visible {
  visibility: visible;
}

你可能會認為所有元素會被隱藏,但父元素會隱藏除了自身子元素以外的所有元素。看看這個demo

position: sticky

We've discovered a new feature that now you can create sticky blocks. They will be working the same as fixed blocks but won't hide another blocks. You'd better see it.

我們發現了一個新功能,現在你可以建立sticky塊元素了。這和 fixed 塊元素一樣,但不同的是, sticky 塊元素是不會遮擋另一個塊元素的,最好看看demo

sticky

現在只有 Mozilla 和 Safari 支援這個屬性,但你可以按照下面的方式使用這個屬性:

.sticky {
  position: static;
  position: sticky;
  top: 0px;
}

We will get a sticky block in browsers which support it and a regular block in other programs. It is rather useful for mobile sites where you need to create a movable block which won't substitute others.

如果瀏覽器支援 sticky,則會得到一個 sticky 塊元素,反之會得到一個普通的元素。當你在手機站需要建立一個可以移動的塊元素而不會遮擋其它元素時是非常有用的。

(sticky可以看作是relative和fixed的結合)

New Dimensions

新的尺寸

Not so far this world discovered some new ways to describe sizes of different objects. Here are them:

  • vw (viewport width) – one percent of browser window's width.
  • vh (viewport height) – the same but for height.
  • vmin and vmax choose minimal and maximal value between vh and vw.

現在有一些新的方式來描述不同物件的大小了,如下:

  • vw(視口寬度): 1vw表示瀏覽器視窗寬度的1%
  • vh(視口高度): 1vh表示瀏覽器視窗高度的1%
  • vmin 和 vmax 表示視口高度和寬度兩者中的最小值或最大值。

The interesting thing is that they all are great supported in most of modern browsers so you can freely use them.

有趣的是所有現代瀏覽器都支援它們,你可以自由使用。

Why do we need them? That's because they make all dimensions simpler. You don't have to specify percentage of parent's element size and any other stuff. Just have a look:

為什麼需要它們?因為它們使得所有的尺寸計算變得簡單了。你不需要指定父元素大小的百分比和任何其它的stuff。看程式碼:

.some-text {
    font-size: 100vh;
    line-height: 100vh;
}

vw&vh

或許你可以在螢幕正中間放一個彈出效果了:

.blackSquare {
    background: black;
    position: fixed;
    height: 50vh;
    width: 50vw;
    left: 25vw;
    top: 25vh;
}

看起來是一個很酷的方式,看看Codepen上的示例

在使用這個功能時,也有一些要主要的事項:

  • IE9 會使用vm,而不是vmin
  • IOS 7 在使用vh時有一些Bug
  • 瀏覽器對vmax的支援並不完全

譯者補充:七個你可能不認識的 CSS 單位

Text Decorations

文字裝飾

可以用下面幾行程式碼改變被選中文字的顏色:

*::selection {
    color: #fff;
    background: #000;
}
*::-moz-selection {    
    /*Only Firefox still needs a prefix*/
    color: #fff;
    background: #000;
}

除了定義 color,還能定義 shadow 和 backgrounds。

Block Scroll on Touch Devices

觸控裝置上的塊元素滾動

If you have some blocks with inner scroll in them then you have to add not only overflow: scroll / auto but this line also:

在觸控裝置上,如果你有一些塊元素在內部有滾動,則你不僅需要新增 overflow: scroll / auto,還要新增:

-webkit-overflow-scrolling: touch;

The thing is that mobile browser sometimes don't work with overflow: scroll property correctly and scroll all the page instead of the needed block. -webkit-overflow-scrolling fix this issue. You can see it by adding this to your own project.

這種情況是有時設定了 overflow: scroll,移動端的瀏覽器會滾動整個頁面而不是在需要的塊元素中滾動。-webkit-overflow-scrolling 修復了這個問題。你可以把它新增到你的專案中看看效果。

Using Hardware Acceleration

使用硬體加速

Sometimes your animation can to slow down client's computer. You can use acceleration for special block in order to prevent this event:

有時,你的動畫效果在客戶端的計算機上會減慢,為了防止這種情況發生,你可以為特定的塊元素使用加速:

.block {
    transform: translateZ(0);
}

In statics you won't notice any difference, but browsers will understands that the element should be treated as three-dimensional and will enable acceleration. Until there are no normal support of specifically designed for this property will-change, this method is quite descend.

在靜態情況下你可以不會注意到差別,但瀏覽器會認為這個元素應該被視為 3D 元素並能夠加速。在屬性 will-change 沒有得到正常支援之前,這種方法是很有用的。

Unicode Classes

Unicode 類

現在可以用 Unicode 符號來設定類名:

.❤ {
    ...
}
.☢ {
    ...
}
.☭ {
    ...
}
.★ {
    ...
}
.☯ {
    ...
}

不要在大專案中使用,因為 UTF-8 可能並不被所有計算支援。

Vertical Margines in Percents

在垂直 Margins 上使用百分比

事實上,垂直縮排是根據父元素的寬而不是高來計算的,我們建立兩個塊元素:

<div class="parent">  
    <div class="child"></div>
</div> 
.parent {
    height: 400px;
    width: 200px;
}
.child {
    height: 50%;
    padding-top: 25%;
    padding-bottom: 25%;
    width: 100%;
}

理論上,應該按父元素的高來填充,但是我們得到的效果是相反的:

vertical margins

你應該時刻記住百分比是按照父元素的寬計算的。

譯者補充:CSS 中的百分比

Margins in Firefox Buttons

Firefox的按鈕的Margins計算

對於按鈕的margins計算,Firefox有它自己的方式。

margins

可以使用下面的方式修復:

button::-moz-focus-inner,  
input[type="reset"]::-moz-focus-inner,  
input[type="button"]::-moz-focus-inner,  
input[type="submit"]::-moz-focus-inner {  
    border: none;
    padding:0;
}

Color + Border = Border-Color

並不是所有人知道,通過定義任何物件的文字顏色,也能定義其邊框色:

input[type="text"] {  
    color: red;
    border: 1px solid;
}

border-color

Bonus for Oldies

如果你還要支援 IE7 或其他低版本瀏覽器,你可以用一個smile來定義它們的 Hacks,就像這樣:

body {  
    :) background: pink;
}

原文: 22 Essential CSS Recipes

相關文章