AHB
AHB

Reputation: 212

Correctly centering a fixed <div> element

I used this css to center a fixed <div> block. but it appears at the left bottom corner of <body>. What's the problem?

#console {
    border-width: 1px;
    border-style: solid;
    border-color: black;
    font-size: 16px;
    
    margin: 0  auto;
    position: fixed;
    bottom: 0;
    }
<div id="console">Example</div>

Upvotes: 1

Views: 426

Answers (4)

MartyIX
MartyIX

Reputation: 28648

I would go with:

position: fixed;
bottom: 0;
width: 100px;
left: calc(50% - 50px); // 50px is half of 100px

Live example:

#console {
    border-width: 1px;
    border-style: solid;
    border-color: black;
    font-size: 16px;
    
    position: fixed;
    bottom: 0;
    width: 100px;
    left: calc(50% - 50px); // 50px is half of 100px
}
<div id="console">Example</div>

Note that calc requires modern browsers. More on calc: MDN, spec

This way you say that the element should be 0px from the bottom and it should be in the middle of the screen (but you neeed to take into account that the element has some width, therefore minus 50px).

http://howtocenterincss.com/ - this is quite good to learn about centering in CSS (try to guess how you would do it before you see the result :-))

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because you've set position: fixed on the element, which means that it is taken out of the normal document flow and margin: 0 auto doesn't work on it.

Instead you could set left: 50% and then a negative margin-left equal to half the width. Try this:

#console {
    position: fixed;
    left: 50%;
    width: 100px;
    margin-left: -50px;
    /* your other rules... */
}

Upvotes: 1

digsrafik
digsrafik

Reputation: 101

Fixed position is in collision with your centering the element by margin. Try left:50%; instead of margin: 0 auto;

Upvotes: 0

tdc
tdc

Reputation: 5464

Try this.

margin: 0 auto;
position: fixed;
bottom: 0;
left: 0;
right: 0;
width: 100px // however wide you want it to be

you've done fixed positioning which removes the item from the normal page flow. By default they have a left of 0.

because you used fixed positioning, margin: 0 auto does not work the same way as it does for elements in the normal document flow (such as static). You must use absolute positioning, relative to the items nearest absolute or relatively-positioned parent.

Upvotes: 0

Related Questions