Franck
Franck

Reputation: 1

CSS Margin collapsing using margin: auto;

I searched over Stackoverflow though many posts but I didn't found the solution.

I'm trying to align my text vertically, using margin: auto;

It seems there is a margin collapsing problem, if you wanna check this example:

// HTML
<div class="outer">
    <div class="inner">Hello</div>
</div>

<div class="outer2">
    <div class="inner">Trying to center this text vertically</div>
</div>

// CSS
.inner {
    margin: auto 0;
    height: 20px;
    color: white;
}
.outer {
    background-color: red;
}
.outer2 {
    background-color: blue;
    height: 200px;
}

If you want to play on my code, click here

Upvotes: 0

Views: 96

Answers (5)

Ajaykumar
Ajaykumar

Reputation: 416

you are trying to align the entire inner div by giving margin:auto. You can use text-align: center if you want to align the text. If you need to align the entire div then mention height and width for inner div. I have posted fiddle link please check

http://jsfiddle.net/ajaycoder/n1rz0bts/4/

.inner {
    margin: auto ;

    color: white;
    width:50%;
    border: solid 1px red;
    height:50%;
}

Upvotes: 0

RSSM
RSSM

Reputation: 679

.outer2 {
    display: flex;
    justify-content: center, left;
    background-color: blue;
    height: 200px;
}

Upvotes: 0

Marielitos
Marielitos

Reputation: 11

The display does the magic. Display: table-cell on inner and display: table on outer div. And finally on inner div you put vertical-align: middle or whatever position that you want.

    .inner {
        display: table-cell;
        vertical-align: middle;
        height: 20px;
        color: white;
    }
    .outer2 {
        text-align: center;
        background-color: blue;
        height: 200px;
        display: table;
        width: 100%;
    }

Upvotes: 1

Neinrappeur Zaki
Neinrappeur Zaki

Reputation: 397

I would advise you to use flexbox add this to outer2 class

.outer2 {
    background-color: blue;
    height: 200px;
    display:flex;
    align-items:center;
}

And for horizontal align you can use justify-content:center align-item:center will align items in center of div vertically ,

Upvotes: 0

wmock
wmock

Reputation: 5492

I don't believe there's a good way to vertically align content using margin: auto 0 like you've set it up. To get the inner divs vertically centered, here's a simple way by modifying .inner:

.inner {
    height: 200px;
    color: white;
    line-height: 200px;
}

Upvotes: 1

Related Questions