Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to centre align div horizontally when using flex direction column

Tags:

html

css

flexbox

I have a container that has a table and a div with the display set to flex with flex-direction as the column.

I want to align the div centre align horizontally. Here is the code

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

I have tried justify-content and align-items CSS rules on the container2 class. But these rules are not getting applied. What is the issue?

As the text-align:center is set to the container2 class but still, its child div with class answer is not showing centre aligned text. what could be the possible issue?

Here is the fiddle https://jsfiddle.net/er_markar/nznddv4k/

Thanks!!

like image 540
Sunil Garg Avatar asked Jan 02 '23 13:01

Sunil Garg


1 Answers

To align children within flexbox, set the following to the parent:

1- justify-content to align children along the main/primary axis i.e. vertical axis if parent has flex-direction: column and horizontal axis if parent has flex-direction: row.

2- align-items to align children along the cross/secondary axis i.e. horizontal axis if parent has flex-direction: column and vertical axis if parent has flex-direction: row.

In your case, try:

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

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

like image 81
xuhaib Avatar answered Jan 05 '23 14:01

xuhaib