Showing posts with label css. Show all posts
Showing posts with label css. Show all posts

Wednesday, 28 March 2012

Centring DIV elements

Here's a HTML structure and required CSS:

<div id="container">
  <div class="centered">This is centered div</div>
</div>
#container { text-align:center;}
.centered { margin:0 auto; width:80%; } /* Set the width according to your needs */

Applying "margin: 0 auto;" would be sufficient in a world without IE. In order to get centred div element in IE, you have to set "text-align: center;" for parent element. That parent element could be another div (just like in example), body element (then style definition would be "body {text-align: center}") or anything else. There's also a lot more detailed explanation of this approach here, but I'm too lazy to read the whole article :(.

Already knew this? Good for you! I did have to spend some time reading discussions and long descriptions about this, but didn't find a single concise "here's a solution - copy, paste, and enjoy" answer.

Are there any drawbacks of this method? Haven't found such yet. If you know something that I'm not aware of, please, let me know this in comments.

Are there any alternatives? Yes:

  • I've seen (and used) alternatives where DIV element is being included into a table which is centred. But it is not recommended approach since page structure should be built using DIVs. I know - it's a challenging task, but that's an idea I've got from different discussions.
  • Also I've found a discussion where a fixed-width DIV gets positioned at the centre of parent element and then a negative margin is applied (haven't tried this one, but looks promising). Here's a CSS:
    .centered{
      width: 500px;
      position: relative;
      left: 50%;
      margin-left: -250px; /* half the width of the div */
    }

Thursday, 19 August 2010

IE7 stretches element around text input field

Situation description: one of the application forms has lots of input fields. They're all formatted using table. One main table has two columns, where each of them contains another table with two columns. In each row of the inner table the first cell contains field label and the second cell contains field itself. Whole table is in DIV element with width of 100%.

I received some problem reports from users that by entering large text in the input field (input type="text") of the first column, other column is moving to the left until it completely disappears. Width of the input element is set to 250px. It turns out that IE7 allows input elements to stretch according to the length of entered text. Although width is set to 250px and user sees it as 250px wide, cell is stretched as if input element wouldn't have defined width.

Solution i found is add overflow:hidden style attribute.