首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么这个容器会扩展到视口之外?

为什么这个容器会扩展到视口之外?
EN

Stack Overflow用户
提问于 2020-10-22 05:02:42
回答 2查看 42关注 0票数 0

我有一个包含4个彩色方块的容器。我已经将容器的样式设置为从视口顶部起27px,从左侧起2% (这是可行的)。但是,我希望这个容器的右侧和底部停止在视区,但它却超出了视区。

因此,下例中的块稍微超出了视口。

我做错了什么?

请注意,在下面的代码中,顶行几乎比底行高出30个像素,因为容器并不完全在视区内。

我有一种感觉,它与包装器容器本身有关,特别是与heightwidth有关,因为它考虑到了我在保持100%的高度和宽度的情况下给它的边距,但我不确定。

编辑:当运行下面的代码时,应该很明显存在问题,因为由于包装器溢出,块的大小并不都相等。

代码语言:javascript
运行
复制
body {
  margin:0;
  padding:0;
  overflow: hidden;
  
}


#wrapper {
  position: relative;
  width: 100vw;
  height: 100vh;
  margin-top: 27px;
  margin-left: 2%;
}

.square {
  position: absolute;
  width: 50%;
  height: 50%;
}

#square1 {
  top: 50%;
  left: 0;      
  background-color: blue;
}

#square2 {
  top: 50%;
  left: 50%;      
  background-color: yellow;
}

#square3 {
  top: 0;
  left: 0;      
  background-color: green;
}

#square4 {
  top: 0;
  left: 50%;      
  background-color: red;
}
代码语言:javascript
运行
复制
<div id="wrapper">
  <div id='square1' class="square"></div>
  <div id='square2' class="square"></div>
  <div id='square3' class="square"></div>
  <div id='square4' class="square"></div>
</div>

EN

回答 2

Stack Overflow用户

发布于 2020-10-22 05:09:44

您可以使用calc来计算保证金:

代码语言:javascript
运行
复制
body {
  margin:0;
  padding:0;  
}


#wrapper {
  position: relative;
  width: calc(100vw - 2%);
  height: calc(100vh - 27px);
  margin-top: 27px;
  margin-left: 2%;
}

.square {
  position: absolute;
  
  width: 50%;
  height: 50%;
}

#square1 {
  top: 50%;
  left: 0;
  
  background-color: blue;
}

#square2 {
  top: 50%;
  left: 50%;
  
  background-color: yellow;
}

#square3 {
  top: 0;
  left: 0;
  
  background-color: green;
}

#square4 {
  top: 0;
  left: 50%;
  
  background-color: red;
}
代码语言:javascript
运行
复制
<div id="wrapper">
  <div id='square1' class="square"></div>
  <div id='square2' class="square"></div>
  <div id='square3' class="square"></div>
  <div id='square4' class="square"></div>
</div>

票数 2
EN

Stack Overflow用户

发布于 2020-10-22 05:11:37

边距被添加到widthheigth属性中,因此100vh的高度加上27px的边距将导致元素的底部比视口底部低27px。为了避免这种情况,您可以使用height: calc(100vh - 27px)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64471713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档