使用Flexbox和绝对位置将DIV居中之间的区别

发布于 2025-02-08 14:33:45 字数 333 浏览 1 评论 0原文

如果我有一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

神仙妹妹 2025-02-15 14:33:45

css位置文档文档描述>位置为:

从普通文档流中删除该元素,并且在页面布局中没有创建空间。

因此,从本质上讲,虽然绝对元素看起来像是围绕容器的中心,但它更像是在容器上方的“悬停”和所有容器的子元素(尝试链接中的交互式示例)。这与Flexbox不同,当您的元素通常以容器为中心,同时仍在其内部空间时。

因为Flexbox方法通常是您想要的,所以我会说这是首选的方式。但是,有时您希望绝对定位的行为,在哪种情况下,绝对可以使用位置:绝对

The CSS position documentation describe absolute position as:

The element is removed from the normal document flow, and no space is created for the element in the page layout.

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.

Absolute positioned element is broken from document flow

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文