Center floating DIVs

十年热恋 提交于 2019-12-06 12:55:25

You need to assign width to the parent div like this :

#container
  {               
    text-align:center;
    margin:0 auto;   
    width:150px;    
  }

My Fiddle

I think if you define the width, display: block, margin 0px auto, position:relative it should work.

Try this,

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Center Div</title>
        <style type="text/css">
        #container
        {               
            text-align:center;
            margin:0 auto; 
            width:200px;

        }
        #container div
        {           
            float:left;
            padding:5px;
            display:cell;
        }
        </style>
    </head>
    <body>  
        <div id="container">
                <div style="background-color:yellow">Text 1</div>
                <div style="background-color:lightgreen">Text 2</div>
                <div style="background-color:lightblue">Text 3</div>

        </div>
    </body>
</html>

Any reason why you don't want to use a table?

It might solve the purpose. Tables are not all that evil as they are made out to be ;)

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
        <meta charset="UTF-8" /> 
        <title>Center Div</title> 
        <style type="text/css"> 
        #container 
        {                
            text-align:center; 
            margin:0 auto;
        } 
        #container td
        {   
            padding:5px;
        } 
        </style> 
    </head> 
    <body>   
        <div id="container">
            <table cellpadding="0" cellspacing="0" style="margin-left:auto;margin-right:auto;">
                <tr>
                    <td style="background-color:yellow">Text 1</td>
                    <td style="background-color:lightgreen">Text 2</td>
                    <td style="background-color:lightblue">Text 3</td>
                </tr>
            </table>
        </div> 
    </body> 
</html> 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!