2015-12-10 81 views
0

我在一個div中渲染2個按鈕,並且想要向左和向右浮動一個按鈕。CSS第一個和最後一個子元素

我以爲我可以使用:第一,孩子最後:子元素,但似乎對CSS的:第一胎運行,並且然後在寫的:最後一子標籤

我還使用嘗試:第n個孩子(1)選擇

下面是一個例子:http://www.bootply.com/elg2cP9Usp

編輯:正確的工作代碼,感謝所有:

<div class="container"> 
    <button type="button" class="btn btn-default 1">On</button> 
    <button type="button" class="btn btn-default 2">Off</button> 
</div> 

/* CSS used here will be applied after bootstrap.css */ 
.container { 
     width: 100%; 
     padding 25px 40px; 
    } 

    .container > .btn { 
     min-width: 35%; 
    } 

    .container > .btn:first-child { 
     float: left; 
    } 

    .container > .btn:last-child { 
     float: right; 
    } 
+0

您的聯繫似乎是錯誤的 - 鏈接一個新的腳本上bootply :) –

+0

哈哈只注意到並添加正確的鏈接。 – chinds

+1

請將相關的[MCVE]代碼添加到您的問題;不要只是鏈接到它或外部網站一旦死亡,翻倒或重新組織它的內容,這個問題就失去了所有的價值,並變得毫無意義(最好)。 –

回答

4

/* CSS used here will be applied after bootstrap.css */ 
 

 
.container { 
 
    width: 100%; 
 
    padding 25px 40px; 
 
} 
 
.container > .btn { 
 
    min-width: 35%; 
 
} 
 
.btn:first-child { 
 
    float: left; 
 
} 
 
.btn:last-child { 
 
    float: right; 
 
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" /> 
 
<div class="container"> 
 
    <button type="button" class="btn btn-default">On</button> 
 
    <button type="button" class="btn btn-default">Off</button> 
 
</div>

錯誤的方法的好友,目標按鈕.. !!

+0

完美謝謝。 – chinds

3

:first-child表示法是一種誤導。你需要直接將它應用到你的.btn類。

爲了得到期望的結果嘗試:

.container .btn:first-child { 
    float: left; 
} 

.container .btn:last-child { 
    float: right; 
} 

爲了避免任何按鍵組,以這樣的表現我縮小了選擇到.container .btn

這是您的updated example

+1

完美謝謝。 – chinds

1

您可能想要使用first-of-typelast-of-type選擇器,這些選擇器允許您按類型選擇元素; button在這種情況下:

.container button:first-of-type { 
    float: left; 
} 

.container button:last-of-type { 
    float: right; 
} 

A fork of your code is here.

相關問題