-1

I want to create a square box using CSS of given size. Then add a paragraph of text inside the square and then center the text horizontally in square.

Here is my code:

#myid {
  width: 100px;
  height: 100px;
  text-align: center;
  vertical-align: middle;
}

#myid:after {
  content: 'hello';
}
<div id="myid" />

The issue is I am able to get the square with text hello centered horizontally but not in the middle of the square.

How to fix this issue?

j08691
  • 204,283
  • 31
  • 260
  • 272
learner
  • 6,062
  • 14
  • 79
  • 139
  • This might help https://css-tricks.com/centering-css-complete-guide/ – dantheman Aug 31 '20 at 18:16
  • That's how I solved it I hope that helped. `#myid { position: relative; } #myid:after { content: 'hello'; position: absolute; transform: translate(-50%); left: 50%; }` – Ahmad Dalao Aug 31 '20 at 18:29

1 Answers1

0

The easiest method by far is to use Flexbox. Simple make #myid a flex container and center its items:

#myid {
  /* ... */
  display: flex;
  justify-content: center; /* Horizontally centers */
  align-items: center; /* Vertically centers */
}

In addition, you can now remove text-align: center and vertical-align: center.

JSFiddle example: https://jsfiddle.net/Lg3u0z4d/.

Jacob Lockard
  • 1,195
  • 9
  • 24