【问题标题】:how to centre align div horizontally when using flex direction column使用flex方向列时如何水平居中对齐div
【发布时间】:2018-09-21 10:21:27
【问题描述】:

我有一个容器,其中有一个 table 和一个 div,其中 display 设置为 flexflex-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/

谢谢!!

【问题讨论】:

  • .container2中尝试margin:2.5em auto 0
  • 为什么你的主容器中有第二个容器?问题不属于 ABC 列,答案不属于 DEF 列吗??
  • @Bhuwan 在使用 flexbox 时,一般应该使用justify-contentalign-items 进行对齐。
  • align-items: center; 在我将其放入 .container2 时起作用。这是您的editted fiddle。也许您有错字或在错误的地方使用它?
  • @Tyler 通常是的,但也使用了自动边距。 Bootstrap 4 经常使用它,而且效果很好。

标签: html css flexbox


【解决方案1】:

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

1- justify-content 沿主轴/主轴对齐子级,即如果父级具有flex-direction: column,则为垂直轴,如果父级具有flex-direction: row,则水平轴。

2- align-items 沿交叉/辅助轴对齐子级,即如果父级具有flex-direction: column,则水平轴和垂直轴,如果父级具有flex-direction: row

在你的情况下,尝试:

.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

【讨论】:

    猜你喜欢
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 2016-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    相关资源
    最近更新 更多