CSS中心显示内联块?

2022-01-30 00:00:00 css

我在这里有一个工作代码:http://jsfiddle.net/WVm5d/(您可能需要使结果窗口更大以查看居中效果)

I have a working code here: http://jsfiddle.net/WVm5d/ (you might need to make the result window bigger to see the align center effect)

问题

代码运行良好,但我不喜欢 display: table;.这是我可以使 wrap-class 对齐中心的唯一方法.我认为如果有办法使用 display: block;display: inline-block; 会更好.是否可以通过其他方式解决对齐中心问题?

The code works fine but I don't like to have display: table;. It's the only way I could make the wrap-class align center. I think it would be better if there was a way to use display: block; or display: inline-block;. Is it possible to solve the align center another way?

给容器添加一个固定的 with 不是我的选择.

Adding a fixed with to the container is not an option for me.

如果将来 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;
}

<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>

推荐答案

接受的解决方案对我不起作用,因为我需要一个带有 display: inline-block 的子元素既是水平的又是在 100% 宽度的父对象内垂直居中.

The accepted solution wouldn't work for me as I need a child element with display: inline-block to be both horizontally and vertically centered within a 100% width parent.

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

I used Flexbox's justify-content and align-items properties, which respectively allow you to center elements horizontally and vertically. By setting both to center on the parent, the child element (or even multiple elements!) will be perfectly in the middle.

此解决方案不需要固定宽度,这对我来说不合适,因为我的按钮文本会发生变化.

This solution does not require fixed width, which would have been unsuitable for me as my button's text will change.

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

Here is a CodePen demo and a snippet of the relevant code below:

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

<div class="parent">
  <a class="child" href="#0">Button</a>
</div>

相关文章