Abhishek Gupta
Abhishek Gupta

Reputation: 6615

Vertical align any inline element in any div using margin-auto

I am designing a text field which I want to be appear vertically-middle of a div. I want the black color div to be show vertically center of the blue (id=srch) div.

HTML & CSS:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style type="text/css">

* {
    vertical-align:baseline;
    font-weight: inherit;
    font-family: inherit;
    font-style: inherit;
    font-size: 100%;
    border:0 none;
    outline:0;
    padding:0;
    margin:0;   
}
html {
    height:100%;
}

#outerwrapper {
    width: 90%;
    height: 100%;
    min-height: 100%;
    height: auto !important;
    border: solid thin #333;
}
body {
    height: 100%;
    width: 100%;
}
#header {
    height: 80px;
    width: 100%;
    background-color:#999;
}
input {
    border:solid thin #ab1; 
}
#srch{
    height:50px;
    background-color:#00f;
}
#srch div{
    margin: auto 0 auto 0;
    width: 200px;
    background-color: #000;
}
#contentWrapper {
    width: 100%;
    overflow: auto;
    background-color:#0F0
}

</style>
</head>

<body>
<div id="outerwrapper">
  <div id="header">Header

      <div id="srch">
        <div>
            <input type="tel" name="aa"/>
        </div>
      </div>
  </div>

  <div id="contentWrapper">
    Content Wrapper
  </div>  

</div>
</body>
</html>

My approach: I give the black div top and bottom margin auto but it is not working (also for the horizontal center [left and right margin:auto] it is working). Does margin:auto only work for left and right?

I want to know why this is happening, and I don't want any other solution like:

  1. Display text inline with a vertical-align div.
  2. Display with proper padding or margin.

Upvotes: 0

Views: 2517

Answers (2)

Dipak
Dipak

Reputation: 12190

You need to use some jQuery here to calculate the height of parent container.

Demo - http://jsfiddle.net/tQBVy/

Upvotes: 1

Maehler
Maehler

Reputation: 6331

margin: auto does not work for top and bottom. If margin-top: auto or margin-bottom: auto is specified, their used value is 0. Here's an article about how you can achieve vertical centering.

Upvotes: 2

Related Questions