使用 nth-child 时浮点数不工作

Float left not working when used nth-child

HTML:

<html>
    <head>
            <link rel=stylesheet href='scarychildselector.css'>
    </head>
    <body>
            <div></div>
            <div></div>
            <div>
                    <div></div>
                    <div></div>
            </div>
    </body>
</html>

CSS:

div{
    height:50px;
    width:50px;
}

div:nth-child(1){
    float:left;
    background-color:green;
}

div:nth-child(2){
    float:right;
    background-color:red;
}

chrome中的输出:

我以为window左边两个红框从上到下

这里的问题是最后的div是向左浮动而不是向右浮动我很困惑向左浮动的原因是什么? background-color 属性 工作正常并给出 div 红色,但浮动 属性 不工作。 我只想知道为什么我的代码会这样,为什么那个框不会向右浮动

您的代码和浮点数实际上按照预期的方式工作。问题出在你的理解上。我在下面添加的不是解决方案。我试图解释它的工作方式。请检查。现在检查代码并再次注释 width: 150px; 和 运行,以便您了解其中的区别。

div {
  display: inline-block;
  width: 50px;
  height: 50px;
  margin: 10px;
}
div:nth-child(1) {
  background-color: red;
  float: left;
}
div:nth-child(2) {
  background-color: green;
  float: right;
}
.wrapper {
  width: 150px; //Comment this line
}
<div></div>
<div></div>
<div class='wrapper'>
  <div></div>
  <div></div>
</div>

为了同时对齐一侧的绿色框和另一侧的红色框,您需要将 width: 100% 给包装器(您评论的行)并仅评论 margin: 10px.你可以像下面这样看到它。

div {
  display: inline-block;
  width: 50px;
  height: 50px;
}
div:nth-child(1) {
  background-color: red;
  float: left;
}
div:nth-child(2) {
  background-color: green;
  float: right;
}
.wrapper {
  width: 100%;
}
<div></div>
<div></div>
<div class='wrapper'>
  <div></div>
  <div></div>
</div>

您错误地为 .wrapper 指定了宽度,并且由于所有 div 的宽度均为 50px,因此子 div 将分成两行。但是漂浮是完美的。这就是我在第一个示例中试图说明的内容。