CSS第一个和最后一个子元素

时间:2015-12-10 13:52:17

标签: css twitter-bootstrap

我在div中渲染了2个按钮,想要向左和向右浮动一个按钮。

我假设我可以使用:first-child和last:子元素,但似乎:first-child的css运行,然后由:last-child标签覆盖

我也尝试过使用:nth-​​child(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;   
    }

3 个答案:

答案 0 :(得分:4)

&#13;
&#13;
/* 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;
}
&#13;
<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>
&#13;
&#13;
&#13;

错误的接近伙伴,定位按钮.. !!

答案 1 :(得分:3)

:first-child符号有点误导。您需要将其直接应用于.btn课程。

要获得所需的结果,请尝试:

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

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

为避免任何按钮组行为如此,我将选择器缩小到.container .btn

这是您的updated example

答案 2 :(得分: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.

相关问题