0

After I did some changes, my feedback div no longer centers on screen and I can't figure out why.

To center a element one only have to set the width and then just do margin: 0 auto; That should normally be enough.

The goal is to have the div shown at the top of the screen, centered. You can see my fiddel here:

http://jsfiddle.net/3u3fd/

Code:

#feedback {
  position: fixed;
  top: 0px;
  min-height: 50px;
  width: 300px;    
  margin: 10px auto;
  z-index: 9000;
  font-weight: bold;
  line-height: 24px;
  border: solid 1px #d1d2d1;
  padding: 10px;
  background-color: #f7f2e7;
  display: none;
  border-radius: 5px;  
  -moz-border-radius: 5px; /* FF < 4.0 */
  -webkit-border-radius: 5px;     /* Rounded corners for Safari */ 
}

#feedback span { display: block; float: left;}
#feedback #feedback_icon { width: 24px; height: 24px; overflow: hidden; margin-right: 10px; }
#feedback #feedback_text { height: 24px; line-height: 24px; display: inline-block; }


​
<div class="clearfix" id="feedback" style="display: block;"><span class="dialogFail" id="feedback_icon"></span><div class="" id="feedback_text">Message here</div></div>

Any help appreciated!

Steven
  • 19,224
  • 47
  • 152
  • 257

3 Answers3

5

auto margins do not work on elements with position: fixed.

Instead, you need to do this:

left: 50%;
margin-left: -Xpx;
width: Ypx;
box-sizing: border-box;

Where X = Y/2.

(The box-sizing: border-box ensures that even if you have padding or borders, it will still be centred. If that interferes with the desired width, then remove it and subtract the value of padding-left + border-left-width from the margin-left.)

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

You have a fixed position set. Get rid of it and it will center just fine.

SenorAmor
  • 3,351
  • 16
  • 27
  • Nope, that will not work. The div should be displayed at the top of the screen, end remain there even if you are scrolling. The DIV is located in the footer. – Steven Mar 21 '12 at 08:21
  • @Steven That is not what your original post says. You asked why your div wasn't centered and I explained why. Your later comment adding your "sticky" requirement came after my answer. – SenorAmor Mar 21 '12 at 13:47
  • My original post says: `The goal is to have the div shown at the top of the screen, centered.` @Kolink understood the context and provided correct answer. Thanks trying though :) – Steven Mar 22 '12 at 10:43
  • Again, your original post said nothing about having it remain there after scrolling. – SenorAmor Mar 22 '12 at 13:20
0

In order for margin: 0 auto; to work, the parent element must have a specified width. It can be percentage or units, but it must have it.

For this solution to work in this case, you need to remove the position: fixed; and top declaraions and add a wrapping element.

http://jsfiddle.net/3u3fd/16/

Kyle
  • 65,599
  • 28
  • 144
  • 152