CSS relative positioning with negative value and h

2019-04-07 18:28发布

问题:

I'm trying to negative position a DIV element (in the example is #content), but my problem is the div's container (#wrapper2), gets too much height (actually is the height the #content is giving, but as I'm moving the content up, I would like to decrease the height of #wrapper2 accordingly).

Here I give you an example to show what I'm trying to achieve. If you try the sample, you'll see that footer stays at too many distance from container. I can make a dirty hack here and make footer top:-200px too but then the scroll bar of the window goes over the footer.

<!DOCTYPE html>
<html>
<head>
    <title>Relative positioning demo</title>
    <style>
        /* RESET STUFF */
        html {
          margin:0;
          padding:0;
          border:0;
        }

        body, div, p, h1 {
          margin: 0;
          padding: 0;
          border: 0;
        }
        /* END RESET */

        h1 {
            background-color: yellow;
        }

        p {
            margin-bottom: 1em;
        }

        /* LAYOUT */
        #wrapper1 {
            text-align: center;
            height: 250px;
            background-color: lightgray;
        }
        #wrapper2 {
            background-color: lightblue;
        }
        #content {
            width: 950px;
            margin: 0 auto;
            background-color: white;
            padding: 5px;
            height: 560px;

            /* HERE's my problem */
            position: relative;
            top: -200px;
        }
        #footer {
            background-color: black;
            color: white;
            height: 40px;
            line-height: 40px;
            text-align: center;
        }               
    </style>
</head>
<body>
    <div id="wrapper1">
        <h1>This is my heading</h1>
    </div>
    <div id="wrapper2">
        <div id="content">
            My content here
        </div>
    </div>
    <div id="footer">
        lorem ipsum
    </div>
</body>
</html>

If you have any suggestions, keep in mind that I must see both, the lightgrey and lightblue background (they're images on my site), so margin-top: -200px is not an option (like someone suggested in related questions that I've searched for)

Thanks!

回答1:

Change the top property to margin-top

Demo

        position: relative;
        top: -200px;

changed to

        margin-top: -200px;


回答2:

For future references, what I've finally done is to merge the images on the wrapper1 and wrapper 2 in the same image (they were background patterns), so I only have one wrapper now, and I don't need to relative position the content above the second one, it just goes following the page flow.

In the end I've understood that you can't delete the unwanted height without using some sort of Javascript.