Friday, April 3, 2009

Centering Non-Text Content (Like Buttons) In A Div

Recently I was working on a web form and had the need to center a button below a text box on the form. I was using a table-less layout and I have to admit at first I was stumped. Basically what I had was a div that contained the text box and the button. To center the button I put another div around it and tried setting text-align: center on that div. Of course that didn't work since a button is not text. So I did some searching and learned that the correct way to do this is to set the width on the div containing the element to be centered and then to set margin: 0px auto;. The real key to making this work however (and since I didn't see anyone point this out on the sites that helped me figure this out I'm writing this post now) is to set the width of the div containing the button to be just big enough to contain the button. I originally tried setting the width of the button container div to be the width of the parent container div and my button wasn't centered at all. It was only when I set the width of my button container div to be roughly the width of the button that I started to see it moving towards the center. And when you think about this it makes sense; setting the left and right margins to auto allows the browser to center the div when the page is rendered. But if the div is wider than the element being centered then it is the div being centered rather than the element within it. By matching up the sides of the containing div with the edges of the button we force the centering of the div to take the button with it. Sample code:
  <style type="text/css">
    width: 800px;
    background-color: Wheat;
    width: 85px;
    margin: 0px auto;

  <div id="PageContainer">
    This is an example paragraph.  Isn't it great?
   <div id="CenteredButtonContainer">
    <input type="submit" />

No comments: