Search code examples
csshtmlcentervertical-alignment

How to do vertical center while height is auto?


i got a small issue with some CSS.

My Container got a static width, but a flexible height. Now i want centering my container vertically but i dont know how.

Could you may help me?

section article {
        position: absolute;
        width: 350px;
        height: auto;
        right: 10%;
        z-index: 2;
        background-color: #fff;
        padding: 15px;
        opacity: 0.9;
    }
	<section>
            <article>
                <header>
                    <h1>Headline</h1>
                    <h2>Title</h2>
                </header>
                <p>content content content</p>
            </article>
        </section>


Solution

  • You can center the article vertically by first moving it down 50% and then moving it up 50% of it's own height, resulting in it being centered.

    section article {
        position: absolute;
        width: 350px;
        height: auto;
        right: 10%;
        z-index: 2;
        background-color: #fff;
        padding: 15px;
        opacity: 0.9;
        top: 50%; // move down 50% of container
        transform: translateY(-50%); // move up 50% of it's own height  
    }
    

    Demo