2015-09-25 66 views
1

我在CSS樣式的按鈕類,其中使用的背景圖片,就像這樣:CSS - 使用CSS對象,而不是背景圖像

.button { 
    display: block; 
    background-position: center; 
    background-size: 30px 28px; 
    background-repeat: no-repeat; 
    background-color: transparent; 
    border: 0; 
    width: 100%; 
    background-image: url('foo.png'); 
} 

以.png形狀很簡單 - 它只是一個橙色的圓圈。所以我想用css來繪製它,以避免使用外部資源。所以,我想用下面的CSS對象(其中繪製了一個橙色的圓):

#circle { 
    width: 100px; 
    height: 100px; 
    background: orange; 
    -moz-border-radius: 50px; 
    -webkit-border-radius: 50px; 
    border-radius: 50px; 
} 

是否有某種方式來使用這樣的方式,它會表現得完全一樣background-image巴紐? (我知道我可以創建另一個按鈕類,我將按不同的方式繪製按鈕,但我想重用已經可用的按鈕類)。

+1

基本上,你必須有其需要的背景股利後面一個div,具有內部與另一個DIV新innerdiv CSS類似於:'width:100px; height:100px;保證金:0汽車; padding-top:25%;' – NemanjaT

+0

div-ception ...我知道:)但我更像是一名網頁開發人員,而不是一名網頁設計師,所以我不會將其作爲解決方案發布......有可能更好的方法來做到這一點。 – NemanjaT

回答

1

如何在數據URI中使用SVG?這裏有一個fiddle showing the example和用來產生它的代碼(該鏈接僅僅是194個字符長):

var svg = '<svg xmlns="http://www.w3.org/2000/svg" width="30" height="28">' 
     + '<ellipse cx="15" cy="14" rx="15" ry="14" fill="orange"/></svg>'; 
location.href = 'data:image/svg+xml;base64,' + btoa(svg); 
+0

哇,不知道這樣的事情甚至可能,很棒的提示! – qiubit

+0

請注意,對於IE支持,[SVG](http://caniuse.com/#feat=svg)需要9+才能像['border-radius']一樣工作(http://caniuse.com/#feat=邊界半徑)。 – Pluto

2

這可以使用僞元素來實現,我做了一個fiddle。你可以玩當然的尺寸。

.button { 
    display: block; 
    border: 0; 
    width: 300px; 
    height: 200px; 
    position: relative; 
    background: transparent; 

    /* just to show where the button is */ 
    border:1px solid #000; 
} 
.button:before { 
    content: ''; 
    display: block; 
    background: orange; 
    border-radius: 50%; 
    height: 100px; 
    width: 100px; 

    /* make sure background is behind text */ 
    z-index: -1; 

    /* center circle in button, negative margins = half of circle dimensions */ 
    position: absolute; 
    top: 50%; 
    left: 50%; 
    margin: -50px 0 0 -50px; 

}