使用flex方向列时如何水平居中对齐div

时间:2018-04-11 13:37:36

标签: html css flexbox

我有一个容器,其中包含表格 div display设置为flexflex-directioncolumn <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>

我想水平对齐div中心对齐。这是代码

justify-content

我在align-items课程上尝试了container2text-align:center CSS规则。但是这些规则没有得到应用。有什么问题?

由于container2设置为answer类但仍然是其类QString pass = "test"; QString hash = QString(QCryptographicHash::hash(pass.toLatin1(),QCryptographicHash::Md5).toHex()); qDebug() << hash; 的子div未显示居中对齐的文本。可能是什么问题?

这是小提琴 https://jsfiddle.net/er_markar/nznddv4k/

谢谢!

1 个答案:

答案 0 :(得分:4)

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