如何用百分比绝对定位元素?

How to absolute position an element with percentages?

我有一个元素,我试图将其绝对定位到中心和底部附近。不管我是从右边还是左边做50%,似乎都稍微偏离了中心。

在此屏幕截图中,您可以看到它从中心向左一点。

a.down {
    font-size:70px;
    color:#fff;
    text-align: center;
    bottom:5%;
    position: absolute;
    right: 50%;
}
<a href="#we-are-the-leader" class="down">
    <i class="fa fa-angle-down"></i>
</a>

如果您绝对像那样定位,您将相对于 right 侧定位元素的 edge。您必须使用边距调整元素的宽度,例如:

margin-right: -35px;

但是,这确实需要您知道项目的宽度。

演示:

a.down {
    font-size:70px;
    text-align: center;
    bottom:5%;
    position: absolute;
    right: 50%;
}

/* Added for demo: */
.fa-angle-down:before { 
  content: '■';
}

a.down {
    border: 1px solid red;
    width: 70px;
    margin-right: -35px;
}
<a href="#we-are-the-leader" class="down">
    <i class="fa fa-angle-down"></i>
</a>

此解决方案将使您放置在包装器中的任何内容居中。

HTML:

<div class="my-class">
    <a href="#we-are-the-leader" class="down">
        <i class="fa fa-angle-down"></i>
    </a>
</div>

CSS:

.my-class {
    font-size:70px;
    text-align: center;
    bottom:5%;
    position: absolute;
    width: 100%;
}

注意:宽度设置为100%。

您可以使用如下绝对位置技巧。

body {
    background: navy;
}
a.down {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 5%;
    margin: auto;
    display: table;
    font-size: 70px;
    color: #fff;
}
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

<a href="#we-are-the-leader" class="down">
    <i class="fa fa-angle-down"></i>
</a>

如果您愿意使用 CSS 转换,解决方案非常简单:

a.down {
    font-size:70px;
    color:#fff;
    text-align: center;
    bottom:5%;
    position: absolute;
    right: 50%;
    transform: translateX(50%);
}

由于变换百分比是根据元素的尺寸计算的,使用沿 x 轴的正 50% 平移只是将元素重新定位到其计算宽度的一半的右侧——实现完美的水平对齐。

如果您使用的是 left: 50%,请改用负值进行翻译。

以下是我能想到的四种可能的方式...

  1. 在左侧位置使用calc()您需要知道元素的宽度...
  2. 在左侧位置使用translateX()并添加负百分比。 无需知道元素的宽度。
  3. 如果左侧位置使用简单的 margin-left 并将其设置为元素宽度的负一半。 您需要知道元素的宽度...
  4. left & right 设置为 0 并使用 margin: auto无需知道元素的宽度...

示例(所有元素都在另一个之上,因为位置相同)

CodePen Demo

a.down {
  font-family: 'FontAwesome';
  position: absolute;
  bottom: 5%;
  font-size: 70px;
  color: #fff;
  text-align: center;
  text-decoration: none;
}

a.down:before {
  content: "\f107";
}

a.down-1 {
  left: calc(50% - 22.5px);
}

a.down-2 {
  left: 50%;
  transform: translateX(-50%);
}

a.down-3 {
  left: 50%;
  margin-left: -22.5px;
}

a.down-4 {
  left: 0;
  right: 0;
  margin: auto;
}

这是我的猜测: 尝试将您的 'a' 标签包装到 div "flexed into 1" 中,并在垂直方向上留出 0,在水平方向留出一些 %(尝试找到使 div 居中的最佳 %!),就像这样:

.center{flex : 1;
margin:0 30%;}

你的 HTML 里面 :

<div class="center"></div>

试试吧。

https://jsfiddle.net/LsgL07en/46/