How to keep absolutely positioned element in place when browser window resized
Asked Answered
D

2

8

I have absolutely positioned text so that it sits inside of my header image, but I cannot figure out how to keep it from moving outside of the header when the browser gets re-sized. If the browser window gets re-sized to a smaller size, the text moves outside of the header, but if the browser window gets re-sized to a bigger size, the text keeps moving to the right of the header!

The header is 800px wide and 150px tall, and it's positioned in the middle of the browser window.

Here's my HTML code:

<div id="container">
    <div id="header">
        <img src="images/header.jpg" alt="Site Header Image">
        <h1>Our Site</h1>
        <h2>Catchy slogan...</h2>
    </div>
</div>

Here's my CSS code:

body {
    margin: 0px;
    padding: 0px;
}

#header h1 {
    color: #FFFFFF;
    position: absolute;
    top: 0px;
    left: 305px;
}

#header h2 {
    color: #FFFFFF;
    position: absolute;
    top: 30px;
    left: 330px;
}

#header img {
    width: 800px;
    height: 150px;
    display: block;
    margin-left: auto;
    margin-right: auto;
}
Dogwatch answered 30/1, 2016 at 18:53 Comment(0)
G
4

There are two issues here:

  1. Absolute positioned elements are laid out with respect to a relative positioned parent. You didn't specify that either #container or #header are relative positioned, so everything is aligned with respect to body - probably not what you want.

  2. Your two container divs, #container and #header are full browser width. You want to constrain them to 800px, to match the image, and center them with margin: auto:

#header {
  position: relative;
  width: 800px;
  margin: auto;
}

Here's a Codepen: http://codepen.io/eldarshamukhamedov/pen/dGKJGm

Gabrielagabriele answered 30/1, 2016 at 19:7 Comment(0)
E
1

That is because absolute positioning works relative to the body IF it does not have any parent with position:relative

Add this code

#header {
  width:800px; /* define a width to the header container */
  position:relative; /* see note */
  margin:0 auto; /* centers header horizontally */
}
Excerpt answered 30/1, 2016 at 19:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.