如何水平居中绝对定位 div 的内容

3
我正在使用Font Awesome库。我想将箭头图标水平居中。DIV必须采用绝对定位
我使用了以下代码,但它并不起作用:
.arrow {
   left: 0;
   right: 0;
}

JSFiddle Demo


请在问题本身中包含您的代码。 - gvee
可能是重复的问题:如何在所有浏览器中垂直居中一个div? - gvee
left: 0; right: 0; 移动到绝对定位的父级 div 中。 - Hashem Qolami
1
如果您真的想让父级 div 为绝对定位,请给它一个适当的宽度。从技术上讲,箭头已经居中了,因为您已经给父级 div 设置了 text-align:center; - bzeaman
@gvee 这个标题有点误导人,其实这个问题不是关于居中一个 absolute 定位的 div,而是它的内容。 - Hashem Qolami
5个回答

3
在绝对定位的
中使用width:100%
.home .center {
    position: absolute;
    bottom: 0;
    top:30px;
    text-align: center;
    width:100%;
}

更新的演示代码


我忘记了只有 "width:100%" 。非常感谢 :) - mehmetdemiray

2
这是一个可行的示例。您可以删除.arrow CSS规则,因为它没有任何作用。
.home {
    margin: 0 auto;
    height: 100%;
    width: 100%;
    position: relative;
    margin: 0 auto;
    max-width: 960px;
}

.home .center {
    position: absolute;
    width: 100%;
    bottom: 0;
    top:30px;
    text-align: center;
}

1
尝试这个:

HTML代码:

<div class="home">
   <div class="center">
     <a class="arrow fa fa-long-arrow-down fa-3x" href="#"></a>
  </div>
</div>

CSS 代码:
.home {
     margin: 0 auto;
     height: 100%;
     width: 100%;
     position: relative;
     margin: 0 auto;
     max-width: 960px;
 }

.home .center {
    position: absolute;
    bottom: 0;
    top:30px;
    text-align: center;
}

.arrow {    
}

position: fix; 嗯?!我想你的意思是 fixed - Hashem Qolami
.home是相对的,它必须是绝对定位的。我解决了这个问题。谢谢 :) - mehmetdemiray

1

这应该可以工作,请尝试。

   .home {
    margin: 0 auto;
    height: 100%;
    width: 100%;
    position: absolute;
    margin: 0 auto;
    max-width: 960px;
}

.center {
    position: relative;
    bottom: 0;
    top:30px;
    text-align: center;
}
.arrow
     left: 0;
    right: 0;

作为解释它为什么有效的原因:好的,包装器div必须是绝对定位的,其内容必须相对于包装器内部的位置进行定位。通过这种方式,如果您想添加更多的相对div,则会更容易。

1

我刚刚把你的CSS换上去了,它工作得很好。

.home {
    margin: 0 auto;
 }

.home .center {
  margin: 0 auto;
  text-align: center;
}
.arrow
   margin: 0 auto;    
}

干杯!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接