0

I have a div with width 100px and height 100px, but I want the text to be aligned in the middle of the div.

I have used text align center for the horizontal alignment, for vertical alignment i tried using vertical-align property. It's not working, then I used line-height for making the content exactly in the middle of the document. The line height will vary for each and every element depending upon the content. Is there any appropriate solution for this issue?

<!DOCTYPE html>
<html>
<head>
<style>
    .dragg-elem div {
      width: 100px;
      height: 100px;
      border: 2px solid #ccc;
      display: inline-block;
      line-height: 90px;
      text-align:center;
    }
</style>
</head>
<body>
    <div class="dragg-elem">
        <div id="one">1</div>
        <div id="two">2</div>
        <div id="three">3</div>
        <div id="four">4</div>
        <div id="five">5</div>
    </div>
</body>
</html>
John_ny
  • 577
  • 4
  • 28

3 Answers3

2

You can use flex for this.

You can also view this in full page it will be centered both vertically and horizontally.

Try this

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<!DOCTYPE html>
<html>
<head>
<style>
  .dragg-elem{
    display:flex; 
    align-items:center;
    height:100vh;
    justify-content: center;
  }
.dragg-elem div {
width: 100px;
height: 100px;
border: 2px solid #ccc;
display: inline-block;
line-height: 90px;
text-align:center;
}
</style>
</head>
<body>
<div class="dragg-elem">
    <div id="one">1</div>
    <div id="two">2</div>
    <div id="three">3</div>
    <div id="four">4</div>
    <div id="five">5</div>
</div>
</body>
</html>
Viira
  • 2,754
  • 1
  • 10
  • 30
0

with display:inline-flex; :

.dragg-elem div {
  width: 100px;
  height: 100px;
  border: 2px solid #ccc;
  display: inline-flex;
  justify-content:center;
  align-items:center;
}

Or with line-height; and text-align:center; . But line-height must be equal with box height.

.dragg-elem div {
  width: 100px;
  height: 100px;
  border: 2px solid #ccc;
  display: inline-block;
  line-height: 100px;
  text-align:center;
}
doğukan
  • 14,001
  • 6
  • 27
  • 47
0

Try this:

    margin-left: auto;
    margin-right: auto;
    text-align: center;