Search code examples
htmlcsscss-positionbackground-image

Two elements absolutely positioned at the same place but not showing at the same place


So, I have these two things. One is a transparent button and the other one is an image behind it.

I did that because adding a background didn't work. Here's what I tried:

.top-container > button {
    background-image: url(path-to-image); /* I also tried image() */
    background-repeat: no-repeat
    width: 100px;
    height: 33px;
    color: white;
    border: none;
    font-family: 'CapitalisTypOasis', 'CapitalisTypOasisMedium';
    text-align: center;
    z-index: 2;
    position: absolute;
    top: 1.7em;
    padding: 0;
}

I did all of the tiny variations I could think of, and since my deadline is soon, I put an image behind the button. Works perfectly.

.boutonsim { 
    display: block;
    height: 33px;
    width: 100px;
    position: absolute;
    top: 1.7em;
    z-index: 1;
}

.top-container > button {
    display: block;
    width: 100px;
    height: 33px;
    background-repeat: no-repeat;
    background-color: rgba(255, 255, 255, 0);
    color: white;
    border: none;
    font-family: 'CapitalisTypOasis', 'CapitalisTypOasisMedium';
    text-align: center;
    z-index: 2;
    position: absolute;
    top: 1.7em;
    padding: 0;
}

HTML:

<div class="top-container">
            <img id="img2" src="images/haut.png" />
            <img id="title" src="images/nom.png" />
            <img id="logo" src="images/LOGO.png" />
            <div class="boutonsim" style="right: 80px;"><img src="images/clipart/boutonORIGINAL.png" /></div>
            <button style="right: 80px;">Culture</button>

        </div>

They're supposed to be at the same place but when I open my file in Chrome, they're not. Could anyone help? Thanks.

This is a GIF of the result in a snippet if it can help:

<a href="https://gyazo.com/c849e62e7893453a2b442f2060bce1e4"><img src="https://i.gyazo.com/c849e62e7893453a2b442f2060bce1e4.gif" alt="Image from Gyazo" width="166"/></a>


Solution

  • TL;DR; position them with anything but em.

    The button must have a different font-size than the rest of the dom (which is also default behaviour), which means that the div and the button have different font-sizes. So because you are positioning them with em, they will be positioned differently (div: 27.2px and button: 22.667px), since the CSS compiler looks at the elements font-size to determine the top value in px.