The difference between percentage width for relative and fixed

I have a page where I have two div elements with different relative and fixed positioning.

<div class="outer1">
</div>
<div class="outer2">
</div>

and css

 .outer1{
    width:50%;
    height:500px;
    background:red;
    position:relative;
    }

    .outer2{
    width:50%;
    background:blue;
    height:200px;
    position:fixed;
    }

But the problem is that the actual width of both div elements is different. I gave the width as 50% for both elements, then why is there a difference in help.pase.pack.

+4
source share
6 answers

Your div .outer1accepts width: 50%its parent, i.e. body. While the div is .outer2positioned fixedand therefore the form is removed the normal flow of documents and will position itself in relation to the viewport.

" ", , paddings , , .

reset , .

html, body {
  margin: 0;
  padding: 0;
}
+3

Position:fixed, div (.. ).

viewport .

. .

, " ". - .

.outer div extra long. Body.

margin:0, , .

JSFIDDLE

+3

css,

body{
    margin:0;
    padding:0;
  }
.outer1{
    width:50%;
    height:500px;
    background:red;
    position:relative;
    float:left;
    }
.outer2{
    width:50%;
    background:blue;
    height:200px;
    position:fixed;
    }
+2

what-is-a-css-reset

css reset html, body margin:0;padding:0;

Demo

html, body
    {
     margin:0; 
      padding:0;
    } 
    .outer1{
        width:50%;
        height:500px;
        background:red;
        position:relative;
        float:left;
        }

        .outer2{
        width:50%;
        background:blue;
        height:200px;
        position:fixed;

        }
<div class="outer1"></div>
<div class="outer2"></div>
Hide result
+1

, , css reset normalize .

body {
    margin: 0;
    padding: 0;
}

: , margin .

As you know, position: fixed it is not included in the flow of documents and therefore does not affect margin body.

So, really what you saw was really right. The c element position: fixedwas the 50%entire viewport, while the c element position: relativewas the minus 50%element (which led to it being less wide).bodymargin

+1
source

try the following:

    body
    {
     margin:0; 
      padding:0;
    } 
    .outer1{
        width:50%;
        height:500px;
        background:red;
        position:relative;
        float:left;
        }

        .outer2{
        width:50%;
        background:blue;
        height:200px;
        position:fixed;

        }

DEMO HERE

0
source

Source: https://habr.com/ru/post/1620247/


All Articles