Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically align a div in a parent which has height auto AND min-height set?

I'm stuck on this one.

I want to vertically center a div. Its parent has an unknown height, however, it does have a min-height.

How can I do this?

like image 513
Gaston Flanchard Avatar asked Dec 11 '22 00:12

Gaston Flanchard


1 Answers

Here is one approach using the CSS3 transform property.

Use absolute positioning to place the top edge of the child element at 50% from the top, and then use the transform: translateY(-50%) to adjust for the child's height.

.parent {
    height: auto;
    min-height: 200px;
    border: 1px dotted gray;
    position: relative;
}
.child {
    border: 1px dotted blue;
    position: absolute;
    top: 50%;
    left: 0;
    transform: translateY(-50%);
}
.content {
    margin-left: 100px;
    margin-right: 400px;
}
<div class="parent">
    <div class="child">child</div>
    <div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer facilisis velit ut neque tempor quis cursus tortor suscipit. Curabitur rutrum magna vitae arcu pharetra eget cursus ante accumsan. Nunc commodo malesuada adipiscing. Pellentesque consequat laoreet sagittis. Sed sit amet erat augue. Morbi consectetur, elit quis iaculis cursus, mauris nulla hendrerit augue, ut faucibus elit sapien vitae justo. In a ipsum malesuada nulla rutrum luctus. Donec a enim sapien. Sed ultrices ligula ac neque vulputate luctus. Suspendisse pretium pretium felis, in aliquet risus fringilla at. Nunc cursus sagittis commodo.
    </div>
</div>
like image 193
Marc Audet Avatar answered Jan 14 '23 13:01

Marc Audet