html - Font awesome 图标正在移出其父容器,位置为 :absolute

标签 html css position

我在包装器 div 中有一个很棒的字体图标。包装器 div 具有绝对定位。 Font Awesome 图标也有一个绝对的位置。包装器 div 需要有绝对定位,因为我要把它放在我的标题标签的底部边缘(不包括在提供的代码中)。

当我从 font awesome 图标中删除“position: absolute”时,该图标不再适合父容器。我对为什么会这样感到困惑。图标的父级是“.wrapper”因此,通过绝对定位 Font Awesome 图标,我应该能够将它准确地移动到我想要它进入“.wrapper”的位置,但它正在移动到包装类的外部边框。

这是当图标有 position: absolute:

<header>
    <div class="wrapper">
        <p>Learn more</p>
        <i class="fas fa-angle-down"></i>
    </div>
</header>

CSS:

header .wrapper {
    border: 2px solid red;
    font-size: 400%;
    position: absolute;
    bottom: 0;
    left: 50%;
}

header .wrapper i {
    position: absolute;
}

header .wrapper p {
    align-content: center;
    font-size: 30%;
}

[codepen] https://codepen.io/anon/pen/yZXMzg?editors=1100

这里是当图标没有position: absolute:


header .wrapper {
    border: 2px solid red;
    font-size: 400%;
    position: absolute;
    bottom: 0;
    left: 50%;
}

header .wrapper i {
}

header .wrapper p {
    align-content: center;
    font-size: 30%;
}


[codepen] https://codepen.io/anon/pen/zezwKM

最佳答案

这是预期的行为。

The element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to its closest positioned ancestor, if any; otherwise, it is placed relative to the initial containing block. Its final position is determined by the values of top, right, bottom, and left. https://developer.mozilla.org/en-US/docs/Web/CSS/position

也就是说,当您的图标是 position: absolute 时,父容器会自行调整大小,就好像图标不存在一样(严格来说,图标不占用空间)。因此,虽然您确实可以使用 position: absolute 定位它,但您只需要手动添加间距(例如,在父级上使用填充)为其添加足够的空间。

示例:https://codepen.io/anon/pen/jdwmZz?editors=1100

根据您的需要,将 position: static 设置为 FontAwesome 元素可能更容易(我还将 i 元素放在 p 以避免换行问题)。 https://codepen.io/anon/pen/Odgmvm?editors=1100

关于html - Font awesome 图标正在移出其父容器,位置为 :absolute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54509564/

相关文章:

python - 我们如何使用回调和提供数据框的函数动态地在 Dash Table 中创建数据列

javascript - 防止缩放跨浏览器

html - 我怎样才能让2个div彼此相邻?

HTML CSS h3 iframe 定位

javascript - 如何使用标记的 URL [VBA]

javascript - 当按钮停留在屏幕顶部时页面跳转

html 和 css 试图在我的方程周围获得一些垂直空间

javascript - float 的列样式对齐

CSS 垂直定位 : relative top + absolute bottom

javascript - Jquery fadeOut 函数有时无法正常工作