Search code examples
htmlcssvertical-alignment

Vertically center input inside a div


I want to have the input fields vertically centered inside each div viz. color-1 color-2 color-3
Using vertical-align: middle either in each div or input is not working.

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

input[type="text"]  {
  width:150px;
  height: 30px;
  text-align: center;
}

#color-1 {

  height: 33%;
  background: {{yourName}};
  text-align: center; 
  vertical-align: middle;
}

#color-2{
  height: 33%;
  background: {{color_2}};
  text-align: center; 
  vertical-align: middle;
}

#color-3{
  height: 33%;
  background: {{color_3}};
  text-align: center; 
  vertical-align: middle;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>

<div id="color-1">
  <input type="text" ng-model="color_1" placeholder="Enter Color #1">
  <h1>{{color_1}}</h1>
</div>

<div id="color-2">
  <input type="text" ng-model="color_2" placeholder="Enter Color #2">
  <h1>{{color_2}}</h1>
</div>

<div id="color-3">
  <input type="text" ng-model="color_3" placeholder="Enter Color #3">
  <h1>{{color_3}}</h1>
</div>


Solution

  • You can do this in two ways using display:flex or using display:table,display:table-row and display:table-cell which you need to wrap in another div.

    Using display:flex is better in which you no need to wrap template in another div

    Add the class color for all the color divs

    Style of 'color' class

    .color{
       height:33%;
       display: flex;
       justify-content: center;
       align-items:center;
    }
    

    For more info refer this https://css-tricks.com/snippets/css/a-guide-to-flexbox/