0

I have h1 that has position "absolute" inside div that has position "relative" but when I set my h1 top:50% left:50% it stands in the middle of viewport and not in the middle of parent div. so nearest parent is ignored for some reason.

HTML:

<div class="container">
            <div class="mshobeli">
                <div class="shvili black"></div>
                <div class="shvili red"></div>
                <div class="shvili green"></div>
            </div>
            <div class="pinkfloyd">
                <img src="https://c4.wallpaperflare.com/wallpaper/785/284/983/music-pink-floyd-wallpaper-preview.jpg"
                    alt="pink floyd logo">
                <h2>Pink Floyd</h2>
            </div>

Here is css

.pinkfloyd {
    display: inline-block;
    position: relative;

}

h2 {

    font-size: 30px;
    color: orangered;
    position: absolute;
    top: 50%;
    left: 50%;

}
oto
  • 1
  • 1
  • Please show us the relevant code. See https://stackoverflow.com/help/minimal-reproducible-example In particular we need to see how you have sized the parent div. – A Haworth Feb 28 '23 at 17:44

1 Answers1

0

When you set top/left 50% it moves the h2 element itself, not the text. As a result, the top left corner of the box encompassing the h2 element is moved to where you requested. To center it the way you want, you translate the element (in this case -50% on the X axis - half of itself to the left) - code snippet available. Check out box model and block display for elements.

.pinkfloyd {
    display: inline-block;
    position: relative;

}

h2 {

    font-size: 30px;
    color: orangered;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%);
}
<div class="container">
            <div class="mshobeli">
                <div class="shvili black"></div>
                <div class="shvili red"></div>
                <div class="shvili green"></div>
            </div>
            <div class="pinkfloyd">
                <img src="https://c4.wallpaperflare.com/wallpaper/785/284/983/music-pink-floyd-wallpaper-preview.jpg"
                    alt="pink floyd logo">
                <h2>Pink Floyd</h2>
            </div>
MaFomedanu
  • 120
  • 7