我在这里有一个工作代码:http://jsfiddle.net/WVm5d/(你可能需要让结果窗口更大才能看到对齐中心效果)
题
代码工作正常,但我不喜欢display: table;
.这是我制作包装类对齐中心的唯一方法.我认为如果有一种方法可以使用display: block;
或更好display: inline-block;
.是否有可能以另一种方式解决对中中心?
添加固定的容器对我来说不是一个选择.
如果JS Fiddle链接在未来被破坏,我也会在此处粘贴我的代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
Baz*_*zzz 256
试试这个.我添加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;
}
Run Code Online (Sandbox Code Playgroud)
Spu*_*ley 68
如果你有一个<div>
with text-align:center;
,那么其中的任何文本都将相对于该容器元素的宽度居中.inline-block
为此目的,元素被视为文本,因此它们也将居中.
EdA*_*EdA 57
接受的解决方案对我不起作用,因为我需要一个子元素,display: inline-block
在100%宽度父级中水平和垂直居中.
我使用了Flexbox justify-content
和align-items
属性,它们分别允许您水平和垂直居中元素.通过将两者都设置center
为父元素,子元素(甚至多个元素!)将完全位于中间.
这个解决方案不需要固定的宽度,这对我来说是不合适的,因为我的按钮的文本会改变.
这是CodePen演示和以下相关代码的片段:
.parent {
display: flex;
justify-content: center;
align-items: center;
}
.child {
display: inline-block;
}
Run Code Online (Sandbox Code Playgroud)
<div class="parent">
<a class="child" href="#0">Button</a>
</div>
Run Code Online (Sandbox Code Playgroud)
你也可以通过定位,将父div设置为relative和child div设置为absolute来实现.
.wrapper {
position: relative;
}
.childDiv {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
Run Code Online (Sandbox Code Playgroud)
这将使内联块元素水平居中,而无需修改其父元素的样式:
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%);
Run Code Online (Sandbox Code Playgroud)