Brutus
Brutus

Reputation: 790

Forcing DIV to have the same margin on all sides

I've just spent 3 or 4 hours trying to understand how to get a "symmetric" DIV inside an HTML page that has to be not scrollable.

The DIV must have the same margins from the window on all sides and must contain an IMG whose size should scale according to the window size maintaining it's ratio.

At the following link you can find the best I've been able to do.

As you can see the DIV has the right margins on the left, top and right size but not on the bottom one! Why not? Is there something wrong with the DIV style?

<div style="margin: 50px;">

I hope it's quite clear, thank you for your help! :)

Edit: since on JSFiddle it doesn't appear as it should be I've just uploaded an image about what I get on my browser:

enter image description here

Edit 2: this is the link to the last working solution, thank you all for your help, in particular to dcardoso. :)

Upvotes: 0

Views: 2025

Answers (3)

Aaron
Aaron

Reputation: 10440

Ahhh, I think I get what you're saying. If the page is longer than your div the space on the bottom is greater than the 50px margin.

You have a couple of choices here, this is just one of many.

I'm using calc() to calculate the 100% width/height minus the 50px on each side.

     html, body {
        margin: 0px;
        overflow: hidden;
    }
    .maxSizeElement {
        width: calc(100vw - 100px);
        height: calc(100vh - 100px);
        margin: 50px;
    }

/* OR YOUR COULD USE...  */

    .maxSizeElement {
      position: absolute;
      width: 85vw;
      height: 85vh;
      top: 0;
      right: 0;
       left: 0;
       bottom:0;
       margin:auto;
    }



    <body>
        <div>
            <img class="maxSizeElement" src="https://thelostdigit.files.wordpress.com/2014/05/wp_ss_20140507_0002.png" />
        </div>
    </body>

Upvotes: 1

Felix A J
Felix A J

Reputation: 6470

The page is getting cut because you are using overflow: hidden; for html and body .

when adding style tag inside jsfiddle style, it is not working. so scroll is visible.

Upvotes: 2

Daniel Cardoso
Daniel Cardoso

Reputation: 478

You should add to your body and html tags (doesn't work in jsfiddle) and remove 'overflow: hidden':

position: relative;
height: 100%;

and to your div tag (remove 'margin:50px'):

box-sizing: border-box; /*This allows for the div padding to be included in the height and width size */
height: 100%;
padding:50px;

Upvotes: 2

Related Questions