Trying to center a div inside another div

Discussion in 'CSS' started by tirengarfio, Mar 4, 2010.

  1. #1
    Hi,

    i expected this code below would center "WTF" in a page, but nooo..

    <div style="widht: 200px">
    
    <div style="display: block;
    margin-left: auto; margin-left: auto;">WTF</div>
     
    </div>
    Code (markup):
    Any idea?

    Javi
     
    tirengarfio, Mar 4, 2010 IP
  2. Barry67

    Barry67 Active Member

    Messages:
    117
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    55
    #2
    <div style="width: 200px">
    
    <div align="center" style="display: block;
    margin-left: auto; margin-left: auto;">WTF</div>
     
    </div>
    Code (markup):
    That should work.
     
    Barry67, Mar 4, 2010 IP
  3. jimmy4feb

    jimmy4feb Peon

    Messages:
    56
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    here is solution:

    <div style="width:200px; height:200px; border:1px solid #000FFF;">
    <div style="width:100px; height:100px; margin:auto; border:1px solid #000000;">
    </div>
    </div>

    remove "height" & "border" from both of the divs if you donot need.

    Thanks,

    Jimmy
     
    jimmy4feb, Mar 4, 2010 IP
  4. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #4
    Inner DIV is display:block by default, since it's a block-level element. (why you should NEVER have to say display:block on a DIV) display:block elements inherently expand to the width of the container they are in if you don't state a width on them. You don't set a width on the inner one, it's as wide as the outer one so there's no room FOR margins to do anything.

    Though If all you want to do is center the TEXT inside the inner DIV, that's what text-align is for... in which case why have a inner DIV?

    <div style="width:200px; text-align:center;">Centered</div>

    No extra div needed - NOT that one should be using the STYLE attribute any more than you should the STYLE tag - get that **** into an external stylesheet!

    @barry67 - you should NOT be advocating the use of the deprecated ALIGN attribute. What's next, FONT and CENTER? What is this, 1997? :p
     
    deathshadow, Mar 4, 2010 IP