【问题标题】:Why do background images and absolute position to 50% behave differently?为什么背景图像和 50% 的绝对位置表现不同?
【发布时间】:2013-02-27 00:26:22
【问题描述】:

图像背景位置向左 50% 使背景图像居中,但在绝对定位元素中左 50% 不使 div 元素居中,为什么?

代码如下:

<div style="position:relative;height:100px; background:url(images/demo.jpg) no-repeat 50% 0">
   <div style="min-height:40px; width:140px; background-color:#aaa;position:absolute;top:0;left:50%;">
        heloo this is just a demo
  </div>

【问题讨论】:

    标签: css


    【解决方案1】:

    background-position 属性中声明的相对定位考虑了被定位图像的尺寸,而使用 CSS 位置属性 (top,right,bottom,left) 时仅考虑相对父级的尺寸。

    考虑它的一个好方法是使用最小值和最大值:

    1. 使用0%,效果是一样的:
      • 背景定位的图像紧贴包含元素的左边缘
      • 绝对定位的元素紧贴相对父级的左边缘
    2. 用100%,效果明显不同:
      • 背景定位的图像紧贴包含元素的右边缘
      • 绝对定位元素的左边缘与相对父元素的右边缘对齐

    为解决您的问题,您可以在第二个 div 中添加元素宽度一半的负边距:

    margin-left: -70px;
    

    【讨论】:

      【解决方案2】:

      div 的左侧将在父divleft: 50%; 的中间。要使孩子居中 div 使用 left: 50%;margin-left: -(half the width of child div)

      【讨论】:

        【解决方案3】:

        为了简单起见,我建议直接删除 position:absolute;top:0;left:50%; 并改用 margin: 0 auto;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-04-15
          • 1970-01-01
          • 2012-05-01
          • 1970-01-01
          • 2013-07-17
          • 2015-08-10
          • 2018-09-01
          相关资源
          最近更新 更多