具有位置绝对元素的IE将创建水平滚动

时间:2018-01-18 05:20:05

标签: html css internet-explorer

我想使用position: absolute创建一个居中的元素,但它会在Internet Explorer 11上创建一个水平滚动条。请参阅下面的脚本。这里的任何人都知道如何解决这个问题?

*更新:我发现使用overflow:hidden似乎以某种方式解决了这个问题。但是当container之外还有另一个时,它也将被隐藏。

.container {
  width: 80%;
  margin: 0 auto;
  height: 100vh;
  border: 1px solid green;
  position: relative;
  overflow: hidden; /*This one is not the solution, though*/
}
.content {
  width: 80%;
  height: 30px;
  position: absolute;
  top: 50px;
  left: 50%;
  transform: translate(-50%, 0);
  border: 1px solid red;
}
.another-content {
  width: 40px;
  height: 40px;
  border: 1px solid blue;
  position: absolute;
  bottom: 20px;
  right: -20px;
}
<div class="container">
  <div class="content"></div>
  <div class="another-content"></div>
</div>

3 个答案:

答案 0 :(得分:2)

您需要在IE

中添加绝对位置的以下属性
position: absolute;
top:0;
right: 0;   
left: 0;
bottom:0;   //specify all including bottom:0

答案 1 :(得分:1)

滚动条显示在所有浏览器中,而不仅仅是IE。您可以执行以下操作:

  • 最大的问题是left: 50%width: 80%一起增加了总宽度,并迫使水平滚动条显示在某些浏览器中(例如Internet Explorer和MS Edge)。您将宽度设置为80%,因此将左边框和右边框之间的剩余20%除以最终为10%。只需使用left: 10%即可获得相同的结果,但不会产生水平滚动条的副作用。
  • 此外,当您将大小设置为100%然后添加边框时,这些边框将不在视图中并导致滚动条显示。这在所有浏览器中都是相同的。使用box-sizing: border-box强制浏览器在高度和宽度计算中包含边框。
  • height: 100vh使框高度等于视口。但是,body的默认边距因浏览器而异。您可以将这些边距设置为零body { margin: 0; },或将高度更改为height: 100%,这是body在这种情况下容器的100%。

试试这个:

&#13;
&#13;
.container {
  width: 100%;
  height: 100%;
  border: 1px solid green;
  position: relative;
  box-sizing: border-box;
}

.content {
  width: 80%;
  height: 30px;
  position: absolute;
  top: 50px;
  left: 10%;
  border: 1px solid red;
}
&#13;
<div class="container">
  <div class="content"></div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

感谢您的回复。虽然它们不是直接解决方案,但它们帮助我找到了解决方法。

原因与Racil Hilan所说的一样。当我使用left:50%width:80%时,内容宽度将被累加并创建一个水平滚动,只有IE才会忽略。我的观点是避免创建额外的宽度。这是我解决这个问题的两种方法。

* {
  box-sizing: border-box;
}

.container {
  width: 100%;
  height: 100vh;
  border: 1px solid green;
  position: relative;
}
.content {
  width: 80%;
  height: 30px;
  position: absolute;
  top: 50px;
  left: 0;
  right: 0;
  border: 1px solid red;
  margin: 0 auto;
}

.content-wrapper {
  border: 1px solid black;
  height: 30px;
  position: absolute;
  top: 100px;
  left: 0;
  right: 0;
}

.another-content {
  width: 80%;
  display: block;
  height: 100%;
  border: 1px solid red;
  margin: 0 auto;
}
<div class="container">
  <div class="content"></div>
  <div class="content-wrapper">
    <div class="another-content"></div>
  </div>
</div>

相关问题