1

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>
AHB
  • 212
  • 2
  • 10

4 Answers4

1

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... */
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

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.

tdc
  • 5,174
  • 12
  • 53
  • 102
0

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 :-))

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
MartyIX
  • 27,828
  • 29
  • 136
  • 207
  • @FelixKling Is that calc() a js pre-declared function? or Can I remove it? – AHB Nov 12 '15 at 17:01
  • `calc()` is a CSS function - https://developer.mozilla.org/en-US/docs/Web/CSS/calc (support is good: http://caniuse.com/#search=calc) – MartyIX Nov 12 '15 at 17:04
0

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

digsrafik
  • 101
  • 4