2013-10-14 19 views
1

嘗試了text-align center和margin auto,兩者都不起作用,我不想用「margin hack」進行居中..以div爲中心而不使用margin自動

http://jsfiddle.net/st9AM/1/

.circle{ 

float: left; 
position: relative; 
width: 120px; 
height: 120px; 
border-radius: 50%; 
border: 2px solid #DDD; 
} 

.inner{ 
float: left; 
position: relative; 
width: 60px; 
height: 60px; 
border-radius: 50%; 
border: 2px solid #DDD; 
} 
+2

爲什麼不'保證金auto'? – Praveen

+0

是否具有固定大小的元素?總是120px和60px? –

+1

哪一部分你想在中心? 「+」號或內圈還是兩者? – Hiral

回答

7

首先,使用margin: auto;黑客攻擊

並以圓心內你的圈子,你可以使用定位技術,如position: absolute;。在這裏,我的內圓用position: absolute;,比正與的50%一個值分配topleft性質和比正在使用margin-topmargin-left和扣除heightwidth的1/2。

爲什麼要扣除32px?正如我已經說過我正好在扣除總額的一半widthheight所以這也包括設置爲2px,這使得您在heightwidth元素64px分別您元素的border

vertical-align+符號,現在用line-height財產,我只能看到單個字符垂直對齊(你沒有說,但在技術上我可以假設你在找什麼形狀的),或者你也可以使用vertical-align: middle;但你需要的容器元素設置爲display: table-cell;

Demo


最後但並非最不重要的,你應該巢內圓內span標籤。

.circle{ 
    float: left; 
    position: relative; 
    width: 120px; 
    height: 120px; 
    border-radius: 50%; 
    border: 2px solid #DDD; 
} 

.inner{ 
    text-align: center; 
    line-height: 60px; 
    position: absolute; 
    top: 50%; 
    margin-top: -31px; 
    left: 50%; 
    margin-left: -31px; 
    width: 60px; 
    height: 60px; 
    border-radius: 50%; 
    border: 2px solid #DDD; 
} 
+0

如果你不能改變你的DOM,你可以ping我尋求幫助 –

+1

+1只是一件事,邊界實際上是2px,所以總寬度將是64px和邊距-32px –

+0

@koala_dev ohhh數學:(感謝指出它出來,我以爲它是1 :)只是編輯我的答案... –

1

你有 「浮動:左」 在小圈子裏,你並不需要

//float: left; 

Working fiddle

1

撈出浮左和使用保證金:0汽車;

.circle{ 

     position: relative; 
     width: 120px; 
     height: 120px; 
     border-radius: 50%; 
     border: 2px solid #DDD; 
     margin:0 auto; 
     } 
0

看看這個fiddle。你寫了float:left;並想要將圖像居中。刪除float:left;,它工作正常。

3

Here's更清潔的解決方案。

只有一個HTML元素。

HTML:

<div class='circle'></div> 

CSS:

* 
{ 
    margin: 0; 
    padding: 0; 
} 
.circle, .circle:after 
{ 
    border-radius: 50%; 
    border: 2px solid #DDD; 
    text-align: center; 
} 
.circle 
{ 
    width: 120px; 
    height: 120px; 
    font-size: 0; 
} 
.circle:before { 
    content:''; 
    display: inline-block; 
    height: 100%; 
    vertical-align: middle; 
} 
.circle:after 
{  
    content:'+'; 
    font-size: 20px; 
    padding: 20px 0; /* 2*padding + font size = innerCircle height*/ 
    display: inline-block; 
    vertical-align: middle; 
    width: 50%; 
} 
+0

Nyc解決方案,你得到我的投票,腸我避免使用僞,除非需要,用戶不明白:-D –

相關問題