How does setting parent position to relative and child position to absolute affect div centering with translate?

huangapple go评论52阅读模式
英文:

How does setting parent position to relative and child position to absolute affect div centering with translate?

问题

我想了解将父元素的位置设置为相对,然后将子元素的位置设置为绝对会产生什么效果,我看到许多人经常使用这种技术。

当我尝试使用 translate(-50%,=50%) 居中一个 div 时,我不得不将父元素的位置设为相对,将子元素的位置设为绝对。我想知道,这样做有什么作用?

英文:

I want to understand what does setting the position of the parent to relative and then setting the position of the child to absolute do, I have seen people use this technique many times?

When I tried to center a div using translate(-50%,=50%), I had to set the position of the parent as relative and the position of the child as absolute. I am wondering, what does that do?

答案1

得分: -1

默认情况下,具有 position: absolute 属性的元素将相对于视口进行定位。要相对于不同的元素进行定位,该元素必须是父/祖先元素,该祖先元素需要设置位置(例如 position: relative;position: absolute;)。所提到的绝对定位元素将相对于具有设置 position 属性的最近的父元素进行定位。

翻译设置仅告诉绝对定位的元素相对于父元素的位置。请注意,您的代码中存在错误。不应该有 =。还要注意,现在有其他居中方法,如使用网格布局(Grid)或弹性盒子布局(Flexbox)。

英文:

By default, an element with position: absolute will be positioned in relation to the viewport. To be positioned relative to a different element — which must be a parent/ancestor element — that ancestor element needs have a position set (such as position: relative; or position: absolute;). The absolute element in question will be positioned in relation to the closest parent with position set.

The translate settings just tell the absolute element where to be positioned in relation to the parent. (Note that there's an error in your code. There should be no =.) Also note that there are other methods for centering these days, such as with Grid or Flexbox.

huangapple
  • 本文由 发表于 2023年5月25日 10:31:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76328529.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定