CSS中心显示内联块?

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

问题

代码工作正常,但我不喜欢有display: table;。这是唯一能让包装类对齐居中的方法。我认为如果有一种使用display: block;display: 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>

569483 次浏览

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

试试这个。我添加了text-align: center到身体和display:inline-block包装,然后删除了你的display: table

body {
background: #bbb;
text-align: center;
}


.wrap {
background: #aaa;
margin: 0 auto;
display: inline-block;
overflow: hidden;
}

我只是改变了2个参数:

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

Live Demo

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

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

你不需要使用“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。

只使用:

line-height:50px

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

你也可以这样做定位,设置父div为相对和子div为绝对。

.wrapper {
position: relative;
}
.childDiv {
position: absolute;
left: 50%;
transform: translateX(-50%);
}

接受的解决方案不会为我工作,因为我需要一个display: inline-block的子元素在100%宽度的父元素中水平和垂直居中。

我使用了Flexbox的justify-contentalign-items属性,它们分别允许你水平和垂直地居中元素。通过在父元素上将两者设置为center,子元素(甚至多个元素!)将完全位于中间。

这个解决方案不需要固定的宽度,这将不适合我,因为我的按钮的文本会改变。

这是一个CodePen的演示和下面的相关代码片段:

.parent {
display: flex;
justify-content: center;
align-items: center;
}
<div class="parent">
<a class="child" href="#0">Button</a>
</div>

这将使一个内联块元素水平居中,而不需要修改其父元素的样式:

  display: inline-block;
position: relative;
/* Move the element to the right by 50% of the container's width */
left: 50%;
/* Calculates 50% of the element's width, and moves it by that */
/* amount across the X-axis to the left */
transform: translateX(-50%);