2024-10-23 07:00:05

CSS中心显示内联块?

我有一个工作代码在这里:http://jsfiddle.net/WVm5d/(你可能需要使结果窗口更大,以看到对齐中心效果)

问题

代码工作正常,但我不喜欢有display: table;。这是唯一能让包装类对齐居中的方法。我认为如果有一种使用display: block的方法会更好;或显示:inline-block;。是否可以用另一种方法解决对齐中心问题?

在容器中添加固定的with对我来说不是一个选项。

我也将粘贴我的代码在这里,如果JS提琴链接在未来被打破:

body { background: #bbb; } .wrap { background: #aaa; margin: 0 auto; display: table; overflow: hidden; } .sidebar { width: 200px; float: left; background: #eee; } .container { margin: 0 auto; background: #ddd; display: block; float: left; padding: 5px; } .box { background: #eee; border: 1px solid #ccc; padding: 10px; margin: 5px; float: left; } .box:nth-child(3n+1) { clear: left; } <div class="wrap"> <div class="sidebar"> Sidebar </div> <div class="container"> <div class="box"> Height1 </div> <div class="box"> Height2<br /> Height2 </div> <div class="box"> Height3<br /> Height3<br /> Height3 </div> <div class="box"> Height1 </div> <div class="box"> Height2<br /> Height2 </div> <div class="box"> Height3<br /> Height3<br /> Height3 </div> </div> <div class="sidebar"> Sidebar </div> </div>


当前回答

很棒的文章,我发现最适合我的是添加一个%的大小

.wrap {
margin-top:5%;
margin-bottom:5%;
height:100%;
display:block;}

其他回答

很棒的文章,我发现最适合我的是添加一个%的大小

.wrap {
margin-top:5%;
margin-bottom:5%;
height:100%;
display:block;}

如果你有一个<div> text-align:center;,那么它里面的任何文本都将相对于容器元素的宽度居中。为此,内联块元素被视为文本,因此它们也将居中。

只使用:

行高:50 px

将“50px”替换为与div相同的高度。

我只是改变了2个参数:

.wrap {
    display: block;
    width:661px;
}

现场演示

你不需要使用“display: table”。你的margin: 0自动定心失败的原因是你没有指定宽度。

这样就可以了:

.wrap {
    background: #aaa;
    margin: 0 auto;
    width: some width in pixels since it's the container;
}

您不需要指定display: block,因为默认情况下div将被阻塞。你可能还会丢失overflow: hidden。