在这个 fiddle 中:http://jsfiddle.net/H4F8H/16/
我试图通过包装外部 div 并将其居中来使两个 div 居中:
<div style="margin-left:auto;margin-right:auto;">
但是 div 保持左对齐。如何让这些 div 在页面上居中?
fiddle 代码:
HTML:
<div style="margin-left:auto;margin-right:auto;">
<div id="block">
<img height="50" style="max-width: 50px;background-position: top left;" src="http://socialmediababe.com/wp-content/uploads/2010/12/administrator.jpg" />
<div style="font-size:20px;font-weight:bold;">
Test
</div>
<div>
<a href="http://www.google.com">Google</a>
</div>
</div>
<div id="block">
<img height="50" style="max-width: 50px;background-position: top left;" src="http://socialmediababe.com/wp-content/uploads/2010/12/administrator.jpg" />
<div style="font-size:20px;font-weight:bold;">
Test
</div>
<div>
<a href="http://www.google.com">Google</a>
</div>
</div>
</div>
CSS:
*{
margin:0;
padding:0;
}
#block {
margin-right:100px;
border-width: 2px;
border-color: #4682B4;
background-color: WHITE;
width: 100px;
text-align: center;
line-height:30px;
padding:3px 0;
float:left;
}
img{
float:left;
}
#block:hover {
background-color: #C2DFFF ;
}
最佳答案
div
默认情况下是一个 block 级元素,所以如果你不分配一些 width
它将占用 100% 的水平空间。给它,所以你需要分配一些 width
到你的容器
<div style="margin-left:auto;margin-right:auto; width: 300px;">
在这里,您可以相应地设置宽度。还要避免使用 inline
CSS。
你的 CSS 有点马虎,例如 margin-right:100px;
不是必需的,你也可以使用像这样的速记
margin: 0 auto;
= margin-left:auto; margin-right:auto;
Demo (添加了红色边框只是为了显示边界)
注意:您正在 float 您的元素,因此请确保通过使用 <div style="clear: both;"></div>
清除您的 float 。我已经在提供的演示中完成了,否则您也可以使用下面的代码片段自行清除父级,例如
.clear:after {
display: table;
clear: both;
content: "";
}
关于css - 如何使页面上的div居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18442906/