首页 > 解决方案 > CSS“计算”功能在 Internet Explorer 11 中无法按预期工作

问题描述

我的网页需要在 Chrome 等现代浏览器上运行,但也需要在 IE11 等旧版浏览器上运行。

大部分都有效,但是当我尝试在容器父级中间放置一个按钮时,divcalc (left: calc(50% - 40px);)在 IE11 中不起作用,而是放置在父级容器之外。

这是我的 CSS 代码:

.buttonContainer {
  position: fixed;
  width: 336px;
  height: 62px;
  background-color: #fff;
  display: inline-block;
  text-align: center;
  vertical-align: middle;
  margin-bottom: 10px;
  box-shadow: 0 0 2px 0 #d2d2d2;
}

.button {
  position: fixed;
  left: calc(50% - 40px);
  .color {
    background-color: #ff0033;
    color: #ffffff;
    display: inline-block;
    height: 26px;
    width: 64px;
    margin-top: 10%;
    padding: 8px 16px;
    font-size: 14px;
    cursor: pointer;
    text-align: center;
    vertical-align: middle;
    line-height: 28px;
  }
}

上面将.button在位于中间的现代浏览器中工作buttonContainer,但在 IE11 中它将位于它的外部。

标签: htmlcssinternet-explorersasscross-browser

解决方案


IE 使用 calc 可能有点困难。一种解决方案是设置left50%然后使用转换来更正按钮的宽度,如下所示:

.button {
    left: 50%;
    -moz-transform: translateX(-50%);
    -webkit-transform: translateX(-50%);
    -o-transform: translateX(-50%);
    -ms-transform: translateX(-50%);
    transform: translateX(-50%);  // -50% of the width of the button
}

要记住的另一件事是,位置固定将相对于浏览器窗口定位元素,而不是相对于它的包含元素(除非包含元素是浏览器窗口:)。


推荐阅读