CSS – align text in center horizontally

Text can be aligned in center of a div or any other block level element using CSS property text-align:center. Note that this property applies of any inline (including inline-block) element inside that div. Here are some examples.

Align text in middle horizontally

<style type="text/css">
.container {
  width: 200px;
  height:100px;
  background-color:lightgreen;
  text-align: center;
}
</style>

<div class="container">
  Hello world
</div>
refresh

Align span in middle horizontally

<style type="text/css">
.container {
  width: 200px;
  height:100px;
  background-color:lightgreen;
  text-align: center;
}
.container span {background-color:lightgray;}
</style>

<div class="container">
  <span>Hello world</span>
</div>
refresh

Align input field in middle horizontally

<style type="text/css">
.container {
  width: 200px;
  height:100px;
  background-color:lightgreen;
  text-align: center;
}
</style>

<div class="container">
  <input type="text" name="something" value="value1" />
</div>
refresh
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments