2014-03-04 56 views
3

如何使按鈕同時位於div底部和中間?div中間和底部的按鈕

這裏是我的代碼: http://jsfiddle.net/3QguR/1/

HTML

<div class='Center' align='center'> 
    <button class='btn-bot'>button-bottom</button> 
</div> 

CSS

.Center{ 
    width:200px; 
    height:200px; 
    background:#0088cc; 
    margin:auto; 
    padding:0%; 
    position: relative; 
    top: 0; left: 0; bottom: 0; right: 0; 
    border-radius:5%; 
} 
.btn-bot{ 
    position: absolute; 
    bottom: 0; 

} 
+2

http://jsfiddle.net/3QguR/3/ – Petah

+1

您不應該使用'align'作爲'div'的屬性。在HTML5中,此屬性在div標記中已過時:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div 改爲使用css'text-align:center;'。 – 3dgoo

+0

http://stackoverflow.com/questions/5817233/align-button-at-the-bottom-of-div-using-css是你正在尋找的答案 – mmcrae

回答

10

給父元素......

display: table; text-align: center; 

...及其子元素...

display: table-cell; vertical-align: bottom; 

這樣你不需要知道子元素的寬度,以防它發生變化,因此需要沒有消極的利潤或解決方法。

3

這樣做是給它的絕對寬度的一種方式,然後一保證金的一半:

width: 250px; 
margin-left: -125px; 

另一種方法是給予div以下行高和從button刪除所有樣式:

line-height: 398px; 
+0

CSS不應該包含負值! –

+1

@PratikJoshi這是錯誤的。他們不應該被用於過剩,但有很多情況下,負值是可以接受的 - 不要用我的話來說吧http://coding.smashingmagazine.com/2009/07/27/the-definitive-guide -to-using-negative-margin /和http://stackoverflow.com/a/4990026/1592764 – Marcatectura

2

例如這樣寫,如果你有絕對位置:

.btn-bot{ 
    position:absolute; 
    margin-left:-50px; 
    left:50%; 
    width:100px; 
    bottom:0px; 
} 

注意:給出按鈕寬度的餘量左半部分。

JSFiddle demo

+0

它的工作原理沒有「left:50%;」 我們爲什麼需要它? – nuT707

+0

你需要它,因爲如果你不使用它並且改變了寬度,那麼在那種情況下它就會失敗。看到這個:http://jsfiddle.net/3QguR/18/。所以爲了讓這個例子在所有情況下都可以使用,你需要使用它。 –

+0

當我把它添加到你的失敗的例子沒有任何反應。 – nuT707

3

按鈕是否需要絕對定位?如果是這樣,你可以指定一個寬度,然後負左邊距:

.btn-bot{ 
    position: absolute; 
    left: 50%; 
    width: 100px; 
    margin-left: -50px; 
    bottom:0px; 
} 

fiddle

+0

無論如何定位它。目標是讓按鈕位於底部。 – nuT707

4

您可以使用display: table-cellvertical-align: bottom來實現此目的,儘管您需要將容器格設置爲display: table

HTML

<div class="boxContainer"> 
    <div class="box"> 
     <button>Bottom button</button> 
    </div> 
</div> 

CSS

.boxContainer { 
    display: table; 
} 
.box { 
    width: 200px; 
    height: 200px; 
    background: #0088cc; 
    padding: 2%; 
    display: table-cell; 
    text-align: center; 
    vertical-align: bottom; 
} 

Demo

+0

看起來很有趣,但我需要在div頂部的一些內容 – nuT707

1

我以前table-row文本和按鈕在一個容器中混合:

#out{ 
    display:table; 
    position:absolute; 
} 

#out div#textContainer{ 
    display:table-row; 
} 
#out div#text{ 
    display:table-cell; 
    vertical-align:top; 
} 

#out div#buttonContainer{ 
    display:table-row; 
    text-align:center; 
} 
#out div#button{ 
    display:table-cell; 
    vertical-align:bottom; 
} 

CodePen

1

我知道這已經是很久以前回答,但我不能使用顯示:在父容器上的表,所以我不得不四處尋找另一種方式。

原來,這只是正常工作:

.container{ 
    position:absolute; 
} 
.button{ 
    position:absolute; 
    bottom: 5px; 
    left: 0%; 
    right: 0%; 
    text-align: center; 
} 

編輯:這工作,如果你的按鈕是一個<div>,而不是實際的<button>