-1

I've created a div in HTML:

  .Div {
  border: 1px solid red;
  margin: 1px;
  text-align: center;
  vertical-align: middle;
  font-size: 20px;
  height: 80px;
  }
  ...
    <div class="Div">
    Just testing my Div.
    </div>
  ...

Output: enter image description here

I want the text to be in the middle of this rectangular, vertically and horizontally. How should I make it happen?

To be mentioned, I didn't use this div inside the main body, it's used inside another div; But in that i also have text-align: center;. I don't know if it's important; But i can provide more details about this code if needed.

P.S: I'm very new to css and html. Please accept my apologies if this code doesn't meet some standards.

Community
  • 1
  • 1
Shayan
  • 345
  • 1
  • 3
  • 13

2 Answers2

0

There are several ways to do this. Since you, yourself tried to use vertical-align in the first place, so vertical-align will only work with display: table-cell;. In order to achieve it, you should set your div, display to table-cell and then you should also define a specific width for your div (I just went with 100vw to fill the available viewport).

So your final code should be something like this:

.Div {
  border: 1px solid red;
  margin: 1px;
  text-align: center;
  display: table-cell;
  vertical-align: middle;
  font-size: 20px;
  height: 80px;
  width: 100vw;
}
<div class="Div">
  Just testing my Div.
</div>

But if you want some generic approach for this you should use flexbox instead. In order to use flexbox, you should define three specific properties to meet your requirement.

  1. display: flex;. This will indicate your div as flex items and then their children should follow flex rules.
  2. align-items: center;. This will indicate all of your items should align in the middle of your div horizontally.
  3. justify-content: center;. This will indicate all of your items should align in the middle of your div vertically.

.Div {
  border: 1px solid red;
  margin: 1px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  height: 80px;
}
<div class="Div">
  Just testing my Div.
</div>
SMAKSS
  • 9,606
  • 3
  • 19
  • 34
0

You may use display: flex;, justify-content: center; and align-items: center in your class Div

You may go http://howtocenterincss.com/, to auto-generate the code that centre text, image or div.

.Div {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid red;
  margin: 1px;
  /* text-align: center;
  vertical-align: middle; */
  font-size: 20px;
  height: 80px;
}
<div class="Div">
  Just testing my Div.
</div>
yinsweet
  • 2,823
  • 1
  • 9
  • 21