2015-12-23 14 views
2

我知道定心材料包裹的元素,如果元素是塊級元素和包裝必須有一個固定高度的div這包含的元素必須具有固定的高度。但我在另一個包裝div中的包裝div中有一個按鈕。但不能與{margin auto, 0px;}.不能居中我的元素在其中具有固定高度的另一包裝div有固定高度的div也

我的風格

 .plusBtn 
{ 
width: 35px; 
height: 28px; 
display: block; 
margin-top: auto; 
margin-bottom: auto; 
} 

.food { 
display: block; 

height: 100px; 


} 

我的HTML居中

<div class="col-md-9 restlist" > 
<div class="foodItem"> 
<div class="food"> 
<div class="plusBtn"> 
<button class="btn btn-success" type="button"><span class="glyphicon glyphicon-plus"></span></button></div> 
</div> 
</div> 
</div> 

My Screenshot about the issue

回答

1

你的代碼是如果你知道你的按鈕的寬度和高度(這是這裏的情況)比較容易:位置是50%,從頂部和左側,然後以像素爲單位:

.food { 
    position: relative; 
    height: 120px; 
} 
.plusBtn { 
    width: 35px; 
    height: 28px; 
    position: absolute; 
    top: 50%; 
    left: 50%; 
    margin-top: -14px; 
    margin-left: -17.5px; 
    text-align: center; 
} 

這裏有一個codepen移動回來了,離開它的高度和寬度的一半:http://codepen.io/anon/pen/wMWNoR

(它可能是更安全,使按鍵寬度36像素和利潤率左-18px避免一半的像素值。)

+0

我知道,相對定位是解決這一問題,但隨後的響應中斷的話.. –

+0

沒有沒有,又何必呢? – Johannes

+0

該按鈕確實位於父元素中。當將左值設置爲0%時,它的電源從左側退出。看到SS https://fbcdn-photos-ha.akamaihd.net/hphotos-ak-xft1/t31.0-0/p640x640/12371055_1091816694184194_5213628577665938224_o.jpg –

0

您的顯示應該是inline-block的,那麼你可以通過添加文字居中 - 中心類包裝按鈕(其父),這是.plusBtn類。最後,修改垂直中心做其中最FUID方式,它是沒有實例化一個高度的類,而是使用填充,以獲得所需的高度離孩子在其中。

這是你所需要的:

.food{ 
    width:100%; 
    border:2px solid red; 
    border-radius:10px; 
    padding:27px 0 35px; 
} 

.plusBtn { 
    width: 35px; 
    height: 28px; 
    display: inline-block; 
} 

這裏是一個CODEPEN

相關問題