css 右边距不适用于容器

qeeaahzv  于 2023-05-02  发布在  其他
关注(0)|答案(2)|浏览(115)

我有一个宽度为200vw的容器,我想在左边和右边添加边距,但由于某些原因,右边距不适用

.container {
  width: 200vw;
  display: flex;
  margin: 0 15%;
}

.container>div {
  width: 50%;
  height: 700px;
}

.box-1 {
  background-color: red;
}

.box-2 {
  background-color: blue;
  /* margin-right: 50rem; */
}
<div class="container">
  <div class="box-1"></div>
  <div class="box-2"></div>
</div>
3z6pesqy

3z6pesqy1#

如果你想在两边之间留出空间,你可以给予padding代替margin。

.container {
  width: 200vw;
  display: flex;
  padding: 0 15%;
}
nhaq1z21

nhaq1z212#

为什么你看不到这些变化是因为你的容器“box-2”被“忽略”了,因为你把容器设置为200 vw W3School CSS Units,这意味着它的宽度是视口宽度的两倍
然后,当你把margin-right: 50rem添加到box-2时,它将超过容器的宽度(.container). The Box Model MDN Docs
您可以将您的容器设置为100vw,然后使用CSS顶部/底部/左侧/右侧位置CSS Tricks top / bottom / left / right position来指定应该添加边距的位置:

.container {
  width: 100vw;
  display: flex;
  margin: 0 25%; //top / bottom / left / right
}

或者使用px代替相对长度(rem/em)等。Which is Better to Use in CSS: px, em, or rem W3Docs Article

.box-2 {
  background-color: blue;
  margin-right: 50px; /* This you can adjust */
}

相关问题