如何在使用flex方向为column时将div水平居中对齐

6

我有一个容器,里面包含一个表格和一个 display 设置为 flexdiv,并且 flex-directioncolumn

我想让 div 在水平方向上居中对齐。以下是代码:

<style>
    .container {
        display: flex;
        flex-direction: column;
        border: 1px solid red;
    }

    .mytable {
        width: 100%
    }

    table,
    th,
    td {
        border: 1px solid black;
    }

    .container2 {
        margin: 2.5em 0 0;
        display: flex;
        max-width: 30%;
        text-align: center;
    }

    .question {
        padding: 5px 20px;
        line-height: 20px;
        font-size: 14px;
        min-width: 50%;
        background-color: green;
        border: 1px solid rgba(27, 31, 35, 0.2);
        border-top-left-radius: 18px;
        border-bottom-left-radius: 18px;
        color: white;
    }

    .answer {
        background-color: blue;
        padding: 5px 20px;
        line-height: 20px;
        font-size: 14px;
        min-width: 50%;
        border: 1px solid rgba(27, 31, 35, 0.2);
        border-top-right-radius: 18px;
        border-bottom-right-radius: 18px;
        color: white;
    }
</style>
<div class="container">
    <div>
        <table class="mytable">
            <tr>
                <th>ABC</th>
                <th>DEF</th>
            </tr>
        </table>
    </div>

    <div class="container2">
        <span class="question">What is your Name</span>
        <span class="answer">Sunil Garg</span>
    </div>

</div>

我已经尝试在container2类上使用justify-contentalign-items CSS规则,但这些规则没有被应用。问题出在哪里?

虽然将text-align:center设置为container2类,但其子div的类answer仍未显示居中对齐的文本。可能的问题是什么?

这是代码片段: https://jsfiddle.net/er_markar/nznddv4k/

谢谢!!


2
尝试在.container2中使用margin: 2.5em auto 0 - Bhuwan
@Bhuwan 当使用flexbox时,通常应该使用justify-contentalign-items进行对齐。 - Tyler
当我将 align-items: center; 放置在 .container2 中时,它起作用了。这是您的已编辑的fiddle。也许您有一个拼写错误或将其放错了位置? - Tyler
https://stackoverflow.com/a/49603779/7427111 - Dhaval Jardosh
@Tyler margin也用于对齐项目。请阅读此链接:https://dev59.com/tlwY5IYBdhLWcg3wgX6V - Bhuwan
显示剩余5条评论
1个回答

11

要在 flexbox 中对齐子元素,请将以下内容设置为父级:

1- 对于主轴(例如如果父元素具有flex-direction: column则为垂直轴,如果父元素具有flex-direction: row则为水平轴),使用justify-content来对齐子元素。

2- 对于交叉轴(例如如果父元素具有flex-direction: column则为水平轴,如果父元素具有flex-direction: row则为垂直轴),使用align-items来对齐子元素。

在您的情况下,请尝试:

.container {
    display: flex;
    flex-direction: column;
    border: 1px solid red;
    justify-content: center; /* align children centered vertically */ 
    align-items: center; /* align children centered horizontally */
}

并且从您用来对齐子元素的子元素中移除 margin

and remove margin from children that you are using to align children.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接