Search code examples
htmlcssposition

Font awesome icon is moving outside of its parent container with position:absolute


I have a font awesome icon in a wrapper div. The wrapper div has a positioning of absolute. The font awesome icon also has a position of absolute. The wrapper div needs to have absolute positioning because I am going to put it on the bottom edge of my header tag (not included in the code provided).

When I take away "position: absolute" from the font awesome icon, the icon no longer fits in the parent container. I'm confused on why this is happening. The parent to the icon is '.wrapper' Therefore, by absolutely positioning the font awesome icon, I should be able to move it exactly where I want it to go inside '.wrapper', but instead it is moving outside of the wrapper class's border.

Here is when the icon has 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

Here is when the icon does not have 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


Solution

  • This is expected behavior.

    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

    That is to say, when your icon is position: absolute, the parent container sizes itself as if the icon was not there (strictly, the icon takes up no space). So while you can indeed position it using position: absolute you'll just need to manually add spacing (e.g. using padding on the parent) to add enough space for it.

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

    Depending on your needs here it may be easier to just position: static to FontAwesome element (I also put the i element inside the p to avoid line break issues). https://codepen.io/anon/pen/Odgmvm?editors=1100