Im trying to center 3 floating DIVs. It works if I give the parent DIV display:table; and the child DIVs display:cell; which will then act like a table. Is there another way ?
<!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;
display:table;
}
#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>
You need to assign width to the parent div
like this :
#container
{
text-align:center;
margin:0 auto;
width:150px;
}
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>
来源:https://stackoverflow.com/questions/11683994/center-floating-divs