为什么我的HTML中的top:和left:属性不一致?

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

Why are the top: and left: properties inconsistent in my HTML

问题

在我的HTML页面中,我有一堆图片框架图片,我正在尝试将它们排列在一个架子图片上,我试图通过使用JavaScript生成每个图片的top:和left:位置(以像素为单位)来完成这个任务。每个img元素都是相同的,除了它们的ID和它们的top:和left:位置不同,但由于某种奇怪的原因,left:60px在一个元素的左边和另一个元素的左边之间的距离是不同的。提供的图像演示了这一点。

以下是包含它们的架子div的CSS样式。每个img元素的position属性都是相对的。

#theShelf {
    background-image: url(sprites/shelf2.png);
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;
    height: 1920px;
    width: 1080px; 
    margin: 0 auto;
}

我原本期望在同一个div中,具有相同top:px和left:px属性、相同尺寸和属性的元素应该在同一个位置。但似乎许多这些元素的位置与它们的数值不一致。我尝试过将每个元素的position类型更改为我能想到的所有选项,但似乎都不起作用。

为什么我的HTML中的top:和left:属性不一致?

英文:

In my HTML page I have a bunch of pictureframe images I'm trying to line up on a shelf image, I'm trying to complete this by generating top: and left: in px the position of each image with javascript. Each img element is identical with the exception of its ID and its top: and left: position, but for some weird reason left:60px will be a different distance from the left of one element to another. The image provided demonstrates this.

Here is my css for the shelf div they are contained in. Each of the img elements have position relative

#theShelf {
    background-image: url(sprites/shelf2.png);
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;
    height: 1920px;
    width: 1080px; 
    margin: 0 auto;
  }

I was expecting an element with the same top:px and left:px properties in the same div, with the same dimensions and properties to be in the same place. But it seems many of these elements have inconsistent positions to their numeric values. I have tried changing the position: type of each element to everything I can think of and nothing seems to work.

为什么我的HTML中的top:和left:属性不一致?

答案1

得分: 2

position: relative 意味着“计算出如果此元素没有定位时它将位于何处,然后从该位置移动它”。

如果你有两个相邻的 <img> 元素而没有进行定位,那么浏览器会将它们放置在一起(即不重叠在同一位置)。

要使用你的方法,你应该考虑在父元素上设置 position: relative 以建立一个包含块,然后使用 position: absolute 来布局其中的各个图像。

也许你不使用定位,而是切换到网格布局会更好。

英文:

position: relative means "Work out where this element would be if it wasn't positioned, then move it from that location".

If you have two &lt;img&gt; elements next to each other without positioning then the browser will render them next to each other (i.e. not overlapping on the same spot).

To use your approach you should be looking at setting position: relative on a parent element to establish a containing block and then using position: absolute to lay out the individual images within it.

You might be better off not using positioning and switching to grid instead.

huangapple
  • 本文由 发表于 2023年2月27日 09:58:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75576220.html
匿名

发表评论

匿名网友

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

确定