【问题标题】:Translate(-50%, -50%) and position: relative issue on different browsers翻译(-50%,-50%)和位置:不同浏览器上的相对问题
【发布时间】:2017-08-20 20:43:27
【问题描述】:

我在尝试将元素翻译 -50%、-50% 时遇到问题。

我的代码如下,但它在 Firefox 和 Chrome 中的执行方式不同。 Firefox 呈现了我想要实现的目标(类 .two 的元素的中心位置),但 Chrome 只是失去了它。

到目前为止,我发现它可能是 position: relative 的情况,但我需要它而不是 absolute 来计算元素相对于父元素的宽度和高度。

body, html {
  height: 100%; width: 100%;
  margin: 0; padding: 0;
}

.one {
  background: red;
  width: 100%;
  height: 100%; /* for anothet purposes */
  min-height: 30%;
  max-height: 50%;
}

.two {
  background: orange;
  display: inline-block;
  height: 80%;
  width: auto; max-width: 90%;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
<div class="one">
<div class="two">ABC</div>
</div>

【问题讨论】:

  • relative 更改为absolute
  • @friedman 为什么将height: 80% 设置为two
  • 谢谢你,Jer,但我需要它相对如上所述。
  • @kukkuz - 我只需要这个元素是 .one 高度的 80%。

标签: html css


【解决方案1】:

这里的问题是容器元素没有明确设置height。没错,它有 min-heightmax-height 集,但没有 height 属性。 (即使计算出的高度是min-height的值)

现在top: 50% 的意思是:'将元素向下移动容器高度的 50%' 所以:

在 Chrome 中:top: 50% 将内部元素向下移动 50% x 0px(容器的设置高度)= 0px,然后 transform 将其向上移动自身高度的一半。

然而,Firefox 将 top: 50% 解释为容器计算高度的 50%。

如果您在容器上设置了明确的高度,这也将在 Chrome 中工作:

body, html {
  height: 100%; width: 100%;
  margin: 0; padding: 0;
}

.one {
  background: red;
  width: 100%;
  height: 150px; /* for anothet purposes */
  min-height: 30%;
  max-height: 50%;
}

.two {
  background: orange;
  display: inline-block;
  height: 80%;
  width: 80%;
  max-width: 90%;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
<div class="one">
<div class="two">ABC</div>
</div>

【讨论】:

  • 感谢您的回答!不幸的是,我需要按百分比而不是按像素保持高度。
  • 您是否尝试过使用视口单位 (vh) 作为高度 - 也许这可能可行?
猜你喜欢
  • 2018-02-21
  • 2017-11-06
  • 2011-03-11
  • 1970-01-01
  • 1970-01-01
  • 2020-11-02
  • 2015-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多