2013-10-09 38 views
0

如何將居中放置一個可變寬度div的同時沿着規則放置百分比?居中放置左側的可變寬度div:x%

在下面的第一張圖片中,105.4left: 12%。問題是,12%適用於它的最左邊緣,而不是中間。

我該如何定位它,比如說12%,但它的中心位於12%,而不是像它的邊緣,就像下面的第二張圖片一樣?

的代碼見this JSFiddle。我無法使用JavaScript,並且無法修復105.4 div的寬度。

回答

1

div.y換成新的div.c其中width: 24%;text-align: center;集合。 24%12% * 2

jsFiddle

HTML

<div class="x"> 
    <div class="c" style="width:24%;text-align:center;"> 
     <div class="y">105.4</div> 
    </div> 
    <div class="a"> 
     <div class="b" style="width:12%;margin-right:auto;"></div> 
    </div> 
</div> 
+0

,但紅色的酒吧增長.. – avrahamcool

+0

@avrahamcool - 小提琴是演示/測試目的?這只是爲了表明,當「12%」變成另一個數字時,這個OP會「起作用」,如何將它定位,比如說12%,這意味着,答案中的HTML提供了基於'12'的答案%'問題。 –

+0

哦,對不起..我沒有檢查它夠好。 – avrahamcool

-1

當你做對12%畫出紅線。它將以12%結束。所以當你添加一半的時候是6%。我相信它會起作用。

<div class="y" style="left:6%;">105.4</div> 

更新

Demo Fiddle

+0

1.你的演示不顯示你的解決方案。 2.您的解決方案無法按預期工作 – avrahamcool

+0

avrahamcool:我更新了小提琴。希望這會是你想要的 – pixelbyaj

+0

我不是OP大聲笑..你的解決方案不工作。嘗試用'50%'和'25%',你會看到。 – avrahamcool

1

我覺得這是最簡單的解決方案。 您只需指定一個寬度。 (無需觸碰保證金,或左值)

看看這個Demo [多個寬度展示]

這是HTML(添加另一種包裝,搬到你的y

<div class="x"> 
    <div class="a"> 
     <div class="b" style="width:12%;"> 
      <div class="c"><div class="y">105.4</div></div> 
     </div> 
    </div> 
</div> 

CSS:(大部分是從複製)

.x { 
    width: 300px; 
    font-size: 16px; 
    line-height: 20px; 
} 
.y { 
    display: inline-block; 
    background-color: #eee; 
    padding: 0 3px; 
} 
.a { 
    height: 5px; 
    background-color: #007d61; 
} 
.b 
{ 
    height: 100%; 
    background-color: #f00000; 
    position:relative; 
} 
.c 
{ 
    position: absolute; 
    width: 200%; 
    text-align: center; 
    bottom: 100%; 
} 
body { 
    padding: 50px; 
} 
相關問題