3

Does anyone have any comments as to the legality of this CSS method to horizontally centre a DIV (with unknown width) inside a parent DIV. The inner DIV is set to 'display: inline-block;' and its containing DIV uses 'text-align: center;'. The 'display: inline-block;' allows the DIV to be considered as an inline element which allows the 'text-align: center;' to act upon it. The outer div is just a demo container. Any comments?

<div style="height: 100px; width: 700px; outline: 1px dotted blue;">
  <div style="text-align: center;">
    <div style="width: 100px; height: 50px; display: inline-block; outline: 1px solid red;">
    </div>
 </div>
</div>
mikeeverard
  • 53
  • 1
  • 1
  • 7
  • Ledal is everything that work (And meets the law), but this seems to me like some kind of bad solution ... – SergeS Mar 02 '14 at 15:35
  • I'm not sure what it is you are asking but (excluding the extra outer div), I don't see an issue. http://jsfiddle.net/JwXt6/2/ – Paulie_D Mar 02 '14 at 16:15
  • I'm just asking the views of people if the method I've shown has any potential issues. It seems to work fine and I think is legal. – mikeeverard Mar 02 '14 at 16:20
  • Of course it's legal...It's a very good solution. – Paulie_D Mar 02 '14 at 16:35
  • It's completely OK. The only thing you should remember is that giving your `div` the `display: inline-*` value it makes it live in the inline formatting context instead of block formatting context, in the anonymous block box containing the single line box that inherits the `line-height` value of the parent element. So if the inner `div` is smaller in height than that `line-height`, some unwanted vertical spacing may occur, and there might be `vertical-align:baseline` "weirdnesses" if that div has `overflow` [other than](https://www.w3.org/TR/CSS22/visudet.html#line-height) `visible`. – Ilya Streltsyn Jan 10 '18 at 08:32

1 Answers1

0

Margin auto in the inner div should resolve your issue. Try the following.

#outer-element{
   width:600px;
   padding:10px;
   display:block;
}

#inner-element{
   display:block;
   margin:10px auto;
}
felixmosh
  • 32,615
  • 9
  • 69
  • 88
Binita Lama
  • 1,268
  • 1
  • 8
  • 16