使用Flexbox和绝对位置将DIV居中之间的区别
如果我有一个Flexbox,我可以在位置的情况下使用水平和垂直的DIV居中,
justify-content: center;
align-items: center;
可以使用以下代码:绝对
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
两者之间有什么区别,而哪个是更喜欢的方式?
If I have a flexbox, I can center a div horizontally and vertically, using
justify-content: center;
align-items: center;
and I can use the following code in the case of position: absolute
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
What is the difference between the both and which is the more preferred way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
css位置文档文档描述>位置为:
因此,从本质上讲,虽然绝对元素看起来像是围绕容器的中心,但它更像是在容器上方的“悬停”和所有容器的子元素(尝试链接中的交互式示例)。这与Flexbox不同,当您的元素通常以容器为中心,同时仍在其内部空间时。
因为Flexbox方法通常是您想要的,所以我会说这是首选的方式。但是,有时您希望绝对定位的行为,在哪种情况下,绝对可以使用
位置:绝对
。The CSS position documentation describe
absolute
position as:So essentially, while an absolute element looks like it is centered around its container, think of it more like "hovering" above the container and all the container's child elements (Try the interactive example in the link). This is different from flexbox, when your element is normally centered in the container while still taking space inside it.
Because the flexbox way is usually what you want, I would say it is the preferred way. However, sometimes you want the behavior of absolute positioning, in which cases it is absolutely (heh) okay to use
position: absolute
.