使用绝对定位是否被认为是不好的做法? [英] Is it considered bad practice to use absolute positioning?

查看:83
本文介绍了使用绝对定位是否被认为是不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在开发一个网页,在那里我为一个像棋的游戏设置了一个棋盘,还有几个托盘。这一切都使用HTML(使用jQuery用于动态更新作为游戏播放)。在某个地方我认为使用页面中的元素的绝对定位被认为是一种坏习惯,并且它更喜欢使用相对定位。

I was developing a web page, where I was laying out a board for a Chess-like game, along with a couple of piece trays. It's all done using HTML (with jQuery for dynamic updating as the game is played). Somewhere I'd got the notion that using absolute positioning of elements within a page was considered a bad practice, and that it was preferable to use relative positioning.

在努力相对定位太长,我意识到,绝对定位的板元素将是很多,更容易得到正确的...它是。

After struggling with relative positioning for too long, I realized that absolute positioning of the board elements would be much, much easier to get right... and it was.

有人知道相对定位优于绝对的原因?

Is anyone aware of a reason that relative positioning is preferable over absolute? Are there any guidelines or rules of thumb that you apply when deciding which approach to take?

推荐答案

对于象棋的游戏,如你正在开发,使用绝对定位没有什么内在的错误。正如你所说,相对定位和正常流动布局使这类任务相当困难。

For a chess like game such as you are developing, there is nothing inherently wrong with using absolute positioning. As you said, relative positioning and normal flow layout make this sort of task quite difficult.

当然,如果您正在开发一个更标准的网站,例如提供一些公共服务的网站,绝对定位会覆盖浏览器的默认流布局,为许多用户。在这种情况下,我会避免它。

Of course, if you were developing a more standard website, such as a site providing some public service, absolute positioning overrides the default flow layout of browsers and so will reduce accessibility for many users. In this case I would avoid it.

说完之后,绝对定位的一个鲜为人知的好处是它允许在内进行局部绝对定位(相对定位)父元素。说明:

Having said that, a lesser known benefit of absolute positioning is that it allows localized absolute positioning within a (relatively positioned) parent element. To explain:

<div id="parentDIV" style="position:relative">
    <div id="childDIV" style="position:absolute:left:20px;top:20px;">
          I'm absolutely positioned within parentDIV.
    </div>
</div>

这里, childDIV 左侧和从 parentDIV 顶部的20px,整个文档。这可以很好地精确控制页面上的嵌套元素,而不会影响整个页面的流动布局。

Here, childDIV is actually positioned 20px from the left and 20px from the top of parentDIV, NOT the overall document. This gives a nice precise control over nested elements on a page, without sacrificing the overall page flow-layout.

因此,为了回答你的问题(相对定位优于绝对) :我不相信有正确的答案,这取决于你需要建立什么。然而,一般来说,定位(绝对或相对)与默认流布局,我的方法如上所述。

So to answer your question (relative positioning being preferred over absolute): I don't believe there is a correct answer, it depends on what you are needing to build. However in general positioning (absolute or relative) versus default flow layout, my approach is as described above.

这篇关于使用绝对定位是否被认为是不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆