[CSS揭秘]自訂單選框和複選框

來源:互聯網
上載者:User

標籤:前端架構   bbb   簡單介紹   元素   rgba   shadow   項目   複選框   active   

很多Web前端工程師肯定都會遇到過,在項目中,UI設計師跑來跟你說,我這個地方的表單控制項需要設計成這個樣子那個樣子。但是用CSS卻不能夠修改這些控制項的預設樣式,於是乎,只能通過div+javascript技術來進行類比。特別是在如今移動端的崛起時代,更加註重使用者的體驗。於是就更加需要這樣一種hack技術。

如果對如今的前端架構有過瞭解,都會知道組件這個概念。那麼在這些架構中,都會提供一些單選框或複選框按鈕組件。可見大家之前受到表單元素的預設樣式的毒害有多深。

今天先給大家簡單介紹一下如何通過CSS來實現單選框和複選框組件。

原理其實很簡單,單選框就是input[type=‘radio‘]而複選框就是input[type=‘checkbox‘] 利用label元素的for屬性與表單控制項的id相互關聯就能起到觸發開關的作用。而label元素又是可以通過CSS自訂預設樣式的。於是就可以將真正的input標籤隱藏起來。

<input type="checkbox" id="awesome"/><label for="awesome">AweSome!</label>
input[type="checkbox"]{    position: absolute;    clip: rect(0,0,0,0);;}input[type="checkbox"] + label::before{    content: "\a0";    display: inline-block;    vertical-align: 0.2em;    width: 0.8em;    height: 0.8em;    margin-right: 0.2em;    border-radius: 0.2em;    background: silver;    text-indent: 0.15em;    line-height: 0.65;}input[type="checkbox"]:checked + label::before{    content: "\2713";    background: yellowgreen;}input[type="checkbox"]:focus + label::before{    box-shadow: 0 0 0.1em 0.1em #58a;}input[type="checkbox"]:disabled + label::before{    background: gray;    box-shadow: none;    color: #555;}

Awesome!

 

實戰: 開關式按鈕

根據前面介紹的方法,可以很容易類比出一個開關式按鈕,也就是直接修改label標籤樣式使得其看起來和按鈕一致。

input[type="radio"]{    position: absolute;    clip: rect(0,0,0,0);  }input[type="radio"] + label{    display: inline-block;    padding: 0.3em 0.5em;    background: #ccc;    background-image: linear-gradient(#ddd, #bbb);    border: 1px solid rgba(0,0,0,0.2);    border-radius: 0.3em;    box-shadow: 0 1px white inset;    text-align: center;    text-shadow: 0 1px 1px white;}input[type="radio"]:checked + label,input[type="radio"]:active + label{    box-shadow: 0.05em 0.1em 0.2em rgba(0,0,0,0.6) inset;    border-color: rgba(0,0,0,0.3);    background: #bbb;}

Awesome!!

 

原理很簡單,當你掌握了這種方法之後,可以配合JS來實現更多有用的表單控制項組件。

[CSS揭秘]自訂單選框和複選框

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.