【问题标题】:Float left not working when used nth-child使用 nth-child 时浮动不工作
【发布时间】:2019-01-07 20:54:37
【问题描述】:

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 输出:

我以为两个绿色的盒子会在左边,两个红色的盒子会在窗口的右边,从上到下

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

【问题讨论】:

  • 最后一个 div 向右浮动,上面没有元素,所以它在右上角,包裹在你的 div nth(1) 中的第一个 div 向左浮动,因为有两个 div已经将它定位在它们下方,还是我完全误解了您的图表?
  • 使用给定的 CSS 和标记,它的行为与预期的一样。编辑您被要求如何回答的问题,您会得到正确的答案。
  • 图片没有代码,贴出实际代码。
  • 是的,但是您仍然应该以文本形式显示它(以便其他人可以轻松地复制和粘贴它以设置他们自己的示例/测试版本,如果这是必要的),而不仅仅是“代码截图”。 meta.stackexchange.com/questions/22186/…
  • 是的,但是在 SO 我们不想要带有代码的图像,我们想要代码作为文本

标签: html css web css-float


【解决方案1】:

您的代码和浮点数实际上以与预期相同的方式工作。问题在你的理解中。我在下面添加的不是解决方案。我试图解释它的工作方式。请检查。现在检查代码并注释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 将分成两行。但漂浮是完美的。这就是我在第一个示例中试图说明的内容。

【讨论】:

  • @LGSon:当我们使用 float left to nth-child(1) 时,.wrapper 的内部 div 也是另一个 first-child。所以风格也适用于此。他错误地给div 赋予宽度,这也适用于.wrapper,所以两个子div 都不能放在一行中,而这将分成一个新行。但是浮动效果很好。所以我要求更改.wrapper 的宽度,因此他发现了不同之处。谢谢
猜你喜欢
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-23
  • 2012-06-11
相关资源
最近更新 更多