vasekhlav
vasekhlav

Reputation: 419

Aligning an input to a divs center

Let's say I have this code

<div id="content1" width="400px" height="100px">
<input type="text" id="znamkyInput">
</div>

<div id="content2" width="400px" height="100px">
<input type="text" id="znamkyInput">
</div>

And I want the input to be vertically centered into the center of the div. How can I do that?

Upvotes: 0

Views: 54

Answers (5)

Andy G
Andy G

Reputation: 19367

The original html is incorrect and the div's height and width should be supplied in css (or using the style attribute).

To align in the center vertically and horizontally:

#content1 {
    width: 400px;
    height: 100px;
    text-align: center;
    display: table-cell;
    vertical-align: middle;
}

As there are two of these divs immediately next to each other then table-cell will cause them to sit adjacent to each-other, on the same line. I would either wrap each in another div (not a great solution) or place a br tag between them (or some other content).

If the intention is to have several of the divs immediately next to, and below, each-other then I would consider using a table.

Upvotes: 0

Ishan Jain
Ishan Jain

Reputation: 8161

Try this:

HTML:

<div id="content1">
  <div>
      <input type="text" id="znamkyInput"/>
  </div>
</div>

CSS :

#content1
{
    background-color: gray;
    width:400px;
    heigth:100px;
}
#content1 div
{
    margin-left: auto;
    margin-right: auto;
   width: 158px; /*width of your input box*/
}

Working Example

Upvotes: 0

Harjeet Singh
Harjeet Singh

Reputation: 396

Just try the following,

 <div id="content1" width="400px" height="100px">
    <input type="text" style="display:inherit" id="znamkyInput">
 </div>

Upvotes: 0

Aditya Ponkshe
Aditya Ponkshe

Reputation: 3890

Use display:inline-block on the child elements and use text-align:center on the parent. That should do the trick

<div id="content1" style="text-align:center" width="400px" height="100px">
    <input type="text" style="display:inline-block" id="znamkyInput">
</div>

Upvotes: 0

user3127896
user3127896

Reputation: 6563

Just try this. And look at the demo

 #content1 {
    text-align: center;
    }

Upvotes: 1

Related Questions