Stefan
Stefan

Reputation: 1071

Margin moves div outside window

I the following html and css:

<div class="foo"></div>

<style>
.foo {
    position: fixed;
    top: 0;
    left: 0;
    background-color: red;
    width: 100%;
    height: 100%;
    margin: 20px
}
</style>

jsfiddle

The Problem is the margin: 20px. Its shifting the whole div to the right and bottom and outside the window. I would expect it to reduce the width of the div, such that the whole element takes 100% of the windows width.

Somehow I cant get this to work. I found solutions, but all of them dont use the fixed position.

Upvotes: 0

Views: 885

Answers (3)

Bmd
Bmd

Reputation: 1317

Why not just assign a position offset of 20px to all 4 sides?

.foo {
    position: fixed;
    top: 20px;
    right: 20px;
    bottom: 20px;
    left: 20px;
    background-color: red;
}

http://jsfiddle.net/brimwd/72rbgr85/

Upvotes: 1

lmgonzalves
lmgonzalves

Reputation: 6588

This is a possible solution:

.foo {
    width: calc(100% - 40px);
    height: calc(100% - 40px);
}

DEMO: https://jsfiddle.net/lmgonzalves/a6nbvmp4/1/

EDIT:

Another possible solution without calc, but with box-shadow:

.foo {
    box-shadow: 0 0 0 20px white inset;
}

DEMO: https://jsfiddle.net/lmgonzalves/a6nbvmp4/6/

Upvotes: 4

Avijit Kumar
Avijit Kumar

Reputation: 538

Just do the following change in your css.

.foo {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom:0;
  background-color: red;
  margin: 20px;
}

JSFIDDLE

Upvotes: 1

Related Questions