Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand a Div Vertically to fit contents

I have Login page, with a div in the center. I have set the height and it fits perfectly. However, if I add validation errors at the top of the div, the button at the bottom gets pushed outside the div. The page is a bit more complicated, but I have simplified it to the following HTML and CSS

<html>
<head>
    <link rel="stylesheet" href="test.css">
</head>
<body>
    <div id="content">
        <form action="/Account/LogIn" method="post">
            <div id="login" name="login">
                <div id="validation-errors">
                    <ul>
                        <li>
                            One or more errors here
                        </li>
                    </ul>
                </div>
                <label>Email:</label> <input type="email" name="email"> <br/>
                <label>Password:</label> <input type="password" name="password"> <br/>
                <input id="loginBtn" type="submit" value="Login" />
            </div>
        </form>
    </div>
</body>
 </html>

And CSS:

#content {
     position: absolute;
     top: 50%;
     left: 0px;
     width: 100%;
     height: 0px;
     overflow: visible;
     visibility: visible;
     display: block;
 }
 #login {
     background-color:#85ADFF;
     width: 350px;
     height: 100px;
     position: absolute;
     top:-100px;
     bottom:0;
     left:0;
     right:0;
     margin:auto;
 }
 #loginBtn {
     float: right;
}

You can view it at http://jsfiddle.net/9jA2F/

What changes should I make so that the Login button stays in the Blue box div even when validation errors are displayed. If you delete the validation error div, it seems to work fine i.e. the button is within the Blue box div.

like image 883
O.O. Avatar asked Dec 08 '25 09:12

O.O.


1 Answers

This method will give you true vertical and horizontal centering regardless of the content height (based on this article)

#content {
    display: table;
    height: 100%;
    overflow: hidden;
    position: relative;
    width: 100%;
}

#content form{
    top: 50%;
    width: 100%;
    text-align: center;
    display: table-cell;
    vertical-align: middle;
    position: static;
}

#login {
    background-color:#85ADFF;
    width: 350px;
    margin-left: auto;
    margin-right: auto;
    position: relative;
    top: -50%;
    text-align: left;
}

Check out the fiddle

like image 171
omma2289 Avatar answered Dec 09 '25 23:12

omma2289



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!