user2889159
user2889159

Reputation:

Centering form into a div block

The following form and css stylesheet are given:

index.html snippet

<div class="parent">
    <div class="child">
        <form>
            <input type="text"/>
            <br/>
            <input type="submit"/>
        </form>
    </div>
    <div class="helper"></div>
</div>

mycss.css snippet

.parent{
    width: 500px;
    height: 400px;
    text-align: center;
    border: 1px solid #dd0;
    background: #ffa;
}
.child {
    display:inline-block;
    vertical-align:middle;
}
.helper {
    display:inline-block;
    vertical-align:middle;
    height:100%;
    width:0px;
}

There is result of code above. But this result isn't clear for me. What is the role of div.helper in this example?

In the div.parent style class we have text-align: center;. Why without it we have only horizontal centering?

Why without vertical-align:middle; in the div.child or div.helper we have only horizontal centering?

Upvotes: 4

Views: 115

Answers (1)

Prasanth K C
Prasanth K C

Reputation: 7332

So here div.helper is used in display:inline-block & vertcal-align:middle mode to make the other one vertically middle to the .parent.

And

text-align: center; is used to make the input elements center to .parent

As said in top,

vertcal-align:middle is used to make those elements vertically center to .parent.

But there were other simple, clean and better ways to do this

Either You can use this simple method to do this:

just change CSS ike this:

Apply diplay:table-cell; to .parent div, So that it will get the ability to align its child vertically middle.

then apply vertical-align:middle to the same to make the child elements vertcally middle

.parent {
width: 500px;
height: 400px;
text-align: center;
border: 1px solid #dd0;
background: #ffa;
display: table-cell;
vertical-align: middle;
}

and remove all other CSS and .helper div

FIDDLE DEMO

Upvotes: 1

Related Questions