Red Ali
Red Ali

Reputation: 49

How to put text in middle of div and position div with margin auto?

I am trying to move text inside the div in middle of the box and I need to move div box in middle of page.

#move {
  border: 4px solid black;
  display: inline-block;
  width: 400px;
  text-align: center;
  height: 200px;
}
<div id="move">Move Me Center</div>

Upvotes: 1

Views: 87

Answers (4)

Devin Luby
Devin Luby

Reputation: 176

If your users mostly use modern browsers, you could always use flexbox as a solution.

Chris over at CSS-Tricks has a great guide to flexbox, here.

Example

Codepen Example

HTML

<div class="flex-container">
<div class="move">
  <p>Move me center</p>
</div>
</div>

CSS

.flex-container { 
  display: flex; 
  flex-direction: row; /* Change to columns for vertical axis */ 
  flex-wrap: wrap; 
  justify-content: center; 
  align-items: center;
  height: 100vh; 
  width: 100vw; 
}

.move { 
  display: flex; 
  align-items: center; 
  justify-content: center; 
  height: 200px; 
  width: 400px; 
  border: 1px solid red; 
}

Upvotes: 0

dippas
dippas

Reputation: 60573

besides using line-height you can create a span around text and apply transform:translateY(50%) and add margin:auto changing inline-block to block in #move

#move {
  border: 4px solid black;
  display: block;
  width: 400px;
  text-align: center;
  height: 200px;
  margin:auto
}
#move span {
  transform: translateY(50%);
  display:block;
  height:100%
}
<div id="move">
  <span>Move Me Center</span>
</div>

Upvotes: 1

Tushar Gupta
Tushar Gupta

Reputation: 15923

  1. : Add margin:auto to make the div to the center
  2. : Add line-height same as the height of the div that is line-height:200px;

#move {
  border: 4px solid black;
  width: 400px;
  text-align: center;
  height: 200px;
  margin:auto;
  line-height:200px
}
<div id="move">Move Me Center</div>

Upvotes: 3

Vingtoft
Vingtoft

Reputation: 14656

Make line-height the same as the height of the div: line-height:200px;

Upvotes: 0

Related Questions