2014-03-04 57 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>