为什么 child 元素在使用 FlexBox 时会卡住

Why child element stick while using FlexBox

当我使用

.flex-container > div 到达所有 child div 元素并收集第三个 div .third

并使用

.third{
  margin-left:auto;
}

body {
  min-height: 100vh;
  width: 80%;
  margin: 5rem auto;
  font-family: Arial, Helvetica, sans-serif;
}

.flex-container {
  display: flex;
  background-color: DodgerBlue;
  padding: 1rem;
}

.flex-container > div {
  background-color: #f1f1f1;
  display: grid;
  place-content: center;
  width:5rem;
  height: 5rem;
  font-size: 3rem;
  margin-right: 1rem;
  margin-left: 1rem;
}

.third{
  margin-left:auto;
}
<div class="flex-container">
      <div>1</div>
      <div>2</div>
      <div class="third">3</div>
</div>

没用。我想知道为什么它不起作用?

然后才发现我还在用

.flex-container > div收集所有childdivs

并去掉 margin-left: 1rem;

body {
  min-height: 100vh;
  width: 80%;
  margin: 5rem auto;
  font-family: Arial, Helvetica, sans-serif;
}

.flex-container {
  display: flex;
  background-color: DodgerBlue;
  padding: 1rem;
}

.flex-container > div {
  background-color: #f1f1f1;
  display: grid;
  place-content: center;
  width:5rem;
  height: 5rem;
  font-size: 3rem;
  margin-right: 1rem;
  /* margin-left: 1rem; */
}

.third{
  margin-left:auto;
}
<div class="flex-container">
      <div>1</div>
      <div>2</div>
      <div class="third">3</div>
</div>

有效。我想知道为什么它像卡住了一样?

当用 .flex-container > * 收集所有 child div 时一切正常

body {
  min-height: 100vh;
  width: 80%;
  margin: 5rem auto;
  font-family: Arial, Helvetica, sans-serif;
}

.flex-container {
  display: flex;
  background-color: DodgerBlue;
  padding: 1rem;
}

.flex-container > * {
  background-color: #f1f1f1;
  display: grid;
  place-content: center;
  width:5rem;
  height: 5rem;
  font-size: 3rem;
  margin-right: 1rem;
  margin-left: 1rem;
}

.third{
  margin-left:auto;
}
 <div class="flex-container">
      <div>1</div>
      <div>2</div>
      <div class="third">3</div>
</div>

那是因为 .flex-container>div 是一个比 .third 更直接的选择器。

基本上,margin-left: auto; 不仅仅适用于 .third

有关 CSS-specificity 的更多信息:https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

请参阅下面的选择器示例 .flex-container>div.third:

body {
  min-height: 100vh;
  width: 80%;
  margin: 5rem auto;
  font-family: Arial, Helvetica, sans-serif;
}

.flex-container {
  display: flex;
  background-color: DodgerBlue;
  padding: 1rem;
}

.flex-container>div {
  background-color: #f1f1f1;
  display: grid;
  place-content: center;
  width: 5rem;
  height: 5rem;
  font-size: 3rem;
  margin-right: 1rem;
  margin-left: 1rem;
}

.flex-container>div.third {
  margin-left: auto;
}
<div class="flex-container">
  <div>1</div>
  <div>2</div>
  <div class="third">3</div>
</div>

这是由于弹性框的行为。弹性盒子是非常动态的,根据它的使用位置可以产生不同的效果。这意味着您必须非常具体地了解 flexbox 中的某个项目,以确保您的意思是准确的。为此,您只能这样解决:

.flex-container div:nth-child(3) { ... },

#third { ... }

.container .third { ... }