【问题标题】:absolute positioning within relative div firefox相对 div firefox 中的绝对定位
【发布时间】:2011-10-13 16:29:47
【问题描述】:

我在相对定位的 div 中对图像进行绝对定位时遇到问题。图像应在 div 中居中。为此,我使用以下 css

div
{
  position: relative;
  top: 0px;
  left: 0px;
}
div img 
{
  margin-top: -10px; /*img width is 20px*/
  position: absolute;
  top: 50%;
}

这适用于除 Firefox 之外的所有浏览器。 有什么解决方法吗?因为我已经为此搜索了很多,但我无法弄清楚。

PS:不要对我说使用 line-height。因为图片旁边还有文字。所以这个选项对我不起作用。

【问题讨论】:

    标签: html css positioning css-position


    【解决方案1】:

    对于你说的图片top: 50%。 50% 什么?它应该是父元素的 50%。父元素设置为什么?如果它没有设置任何东西,那就是问题所在。

    【讨论】:

    • 你在说什么? 50%的父级是div!
    • @McTrafik - 是的,但该 div 未设置为任何内容。所以没有 50% 的参考,因此问题是,50% 是什么?
    【解决方案2】:

    为什么不做这样的事情

    div
    {
      position: relative;
      top: 0;
      left: 0;
    }
    div img
    {
      position: relative;
      top:25%;
      left:50%;
    }
    

    图像的relative 表示从左侧的div 和50% 顶部开始的25%。

    【讨论】:

    • 我试过这个,但top: 25% 什么也没做。左边是工作,但我需要专门的顶部定位
    • 尝试给div一个特定的高度。 IE。图片的大小+填充/边距应该可以工作
    【解决方案3】:

    如果您只想要图片,请尝试将其作为背景图片。

    div
        {
          background-image: url('image.jpg');
          background-position: center;
          background-repeat: no-repeat;
          margin: 0px auto;
          position: relative;
          width: Xpx;
          height: Xpx;
          top: 0px;
          left: 0px;
          vertical-align: middle;
        }
    

    对于文本,使用内部的 div 并使用边距、填充或其他方式定位它。

    【讨论】:

      【解决方案4】:

      自动边距如何:

      div img 
      {
        margin-top: -10px; /*img with is 20px*/
        display: block;
        position: relative;
        margin-left: auto;
        margin-right: auto;
      }
      

      这对我在 Firefox 7 中有效

      【讨论】:

      • 你需要 display: block 和 position: absolute 才能工作,但自动边距适合居中的东西。
      • 水平边距将起作用。但我需要垂直对齐图像
      • 也许我理解错了,但是要垂直对齐图像,您可以使用 'margin-top: 25%;'除了上述。但是您必须手动设置数字 - 自动似乎不起作用。
      【解决方案5】:

      这是一篇来自 CSS-Tricks 的关于该主题的好文章:

      http://css-tricks.com/snippets/css/absolute-center-vertical-horizontal-an-image/

      【讨论】:

        【解决方案6】:

        测试一下:

        div {
            position: relative;
            top: 0px;
            left: 0px;
            background: red;
            width:500px;
        }
        div img {
            margin-top: -10px; 
            //position: absolute; /*get it out*/
            display: block; /*Important*/
            margin: auto; /*Important*/
            top: 50%;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-09-16
          • 1970-01-01
          • 1970-01-01
          • 2012-08-01
          相关资源
          最近更新 更多