3

这是我需要解释的 CSS 片段:

#section {
    width: 860px;
    background: url(/blah.png);
    position: absolute;
    top: 0;
    left: 50%;
    margin-left: -445px;
}

好的,显然这是图像的绝对定位。

  1. top 就像从顶部填充,对吗?
  2. 剩下的 50% 做什么?
  3. 为什么左边距是-445px?

更新: 宽度为 860 像素。实际图像是 100x100 是否有区别?

4

7 回答 7

3
  1. Top 是到 html 元素顶部的距离,或者,如果它在另一个具有绝对位置的元素内,则距该顶部的距离。

  2. & 3. 它取决于图像的宽度,但它可能用于水平居中图像(如果图像的宽度为 890 像素)。不过,还有其他方法可以使图像水平居中。更常见的是,这用于将已知高度的块垂直居中(这是将已知高度的东西垂直居中的最简单方法):

    top: 50%
    margin-top: -(height/2)px;
    
于 2008-09-18T22:43:37.433 回答
3

这可能是为了使页面上的元素居中(使用“死中心”技术)。

它的工作原理是这样的:假设元素是 890px 宽,它被设置为position:absoluteand left:50%,它把它的左边缘放在浏览器的中心(好吧,它可能是其他元素的中心position:relative)。

然后负边距用于将左侧边缘向左移动等于元素宽度一半的距离,从而使其居中。

当然,这可能不会完全居中(这取决于元素的实际宽度,width您粘贴的代码中没有,因此无法确定)但它肯定将元素放置在相对于页面中心的位置

于 2008-09-18T22:46:14.463 回答
2

top 就像从右上角填充?

是的,页面顶部。

剩下的 50% 做什么?

它将内容移动到屏幕的中心(100% 将一直向右。)

为什么左边距是-445px?

用“left: 50%”移动它后,它会向左移动 445 像素。

于 2008-09-18T22:39:32.497 回答
2

上面的代码片段与一个 id 为 section 的元素(可以是 div、span、image 或其他)相关。

该元素有一个 blah.png 的背景图像,它将在 x 和 y 方向上重复。

如果父元素也是绝对定位的,则元素的顶部边缘将位于距其父元素顶部 0px(或任何其他单位)的位置。如果父窗口是窗口,它将位于浏览器窗口的顶部边缘。

该元素的左边缘将位于其父元素左边缘左侧的 50% 处。

然后该元素将从该 50% 点向左“移动”445px。

于 2008-09-18T22:48:52.960 回答
1

通过阅读CSS 盒子模型,你会发现所有你需要知道的东西

于 2008-09-18T22:39:37.943 回答
0

当 position 是绝对值时,top 是到父级的垂直距离(可能是 body 标签,所以 0 是浏览器窗口的上边缘)。左 50% 是距左边缘的距离。负边距将其向左移动 445 像素。至于为什么,你的猜测和我的一样好。

于 2008-09-18T22:37:59.913 回答
0

冒着听起来像显而易见的船长的风险,我将尝试尽可能简单地解释它。

Top 是一个数字,它确定您希望它从其上方的任何 html 元素的顶部开始的像素数......所以不一定是页面的顶部。在设计 css 时要小心你的 html 格式。

Your left to 50% should move it to the center of your screen, given that it's 50. Keep in mind people have different screen sizes and is allocated to the (0,0) top left of your image, not the center of the image, so it will not be perfectly allocated to the center of one's screen like you may expect it to.

THIS is why the margin-left to -445 pixels is used-- to move it further over, fixed.

Good luck, I hope that this made sense. I was trying to word my explanation differently in case other answers were still giving you a hard time. They were great answers as well.

(If you have two different sized monitors, I suggest toying around the with the code to see how each modification affects different sized screens!)

于 2016-01-14T21:37:45.647 回答