证明内容不能与自动保证金一起使用

时间:2019-07-07 15:00:34

标签: html css flexbox

下一页显示两个矩形,红色和蓝色。显示是柔性的。预计红色的页应放置在页面的左侧(margin-right: auto)中,而蓝色的div则应放置在页面的其余部分(justify-content: center)的中心。

但是,结果是蓝色div完全出现在页面的右侧而不是居中。我不了解flexbox。

body {
  display: flex;
  justify-content: center;
}

#redDiv {
  width: 5em;
  height: 10em;
  background-color: red;
  margin-right: auto;
}

#blueDiv {
  width: 10em;
  height: 10em;
  background-color: blue;
}
<div id="redDiv"></div>
<div id="blueDiv"></div>

更新

感谢所有人提供的信息和建议。在它们之后,最终代码为:

body {
  display: flex;
}

#redDiv {
  width: 5em;
  height: 10em;
  background-color: red;
    margin-right: auto;

}

#auxDiv {
  flex: 1 1 auto;
  
  display: flex;
  justify-content: center;
}

#blueDiv {
  width: 10em;
  height: 10em;
  background-color: blue;
}
<!DOCTYPE html>
<html>
<body>

<div id="redDiv"></div>
<div id="auxDiv">
<div id="blueDiv"></div>
</div>

</body>
</html>

更新2:

此解决方案基于Temani Afif的评论,得出相同的结果:

body {
  display: flex;
}

#redDiv {
  width: 5em;
  height: 10em;
  background-color: red;
}

#blueDiv {
  width: 10em;
  height: 10em;
  background-color: blue;
  margin: auto;
}
<!DOCTYPE html>
<html>
<body>

<div id="redDiv"></div>
<div id="blueDiv"></div>
</div>

</body>
</html>

1 个答案:

答案 0 :(得分:2)

使用auto边距后,关键字对齐属性(例如justify-content)无效。 auto边距已使用了所有可用空间。

  

§ 8.1. Aligning with auto margins

     

如果将自由空间分配给自动页边距,则对齐属性   将不会在该维度上产生影响,因为边距将   弯曲后偷走了所有剩余的可用空间。

您要实现的布局在此处进行了描述: