john mangual
john mangual

Reputation: 8172

how to center text inside this <div> element?

Here is an h3 inside a div (using inline styles which I know is bad).

<div style="background-color: rgb(238, 238, 238); width: 500px; height: 36pt; text-align: center;">
<h3 style="font-family: Helvetica;">Hello World!</h3></div>

How can I center the h3 tag inside the div?

Upvotes: 0

Views: 190

Answers (3)

kcNeko
kcNeko

Reputation: 609

you can add line-height which depends on the height of your <div>

<div style="background-color: rgb(238, 238, 238); width: 500px; height: 36pt; text-align: center;">
   <h3 style="font-family: Helvetica; line-height: 36pt">Hello World!</h3>
</div>

take a look at this example fiddle

Upvotes: 1

Aaron Vanston
Aaron Vanston

Reputation: 755

For easy centering vertically you can set the H3 line-height the same as the height of the container (if known).

In this case, we do (as you have set it to 36pt), i.e : line-height: 36pt

Line-height Example:

<div style="background-color: rgb(238, 238, 238); width: 500px; height: 36pt; text-align: center;">
  <h3 style="font-family: Helvetica;line-height: 36pt">Hello World!</h3>
</div>

If the height of the container is dynamic and not known, you will need to use another form of vertically centering, such as using display: table or display:flex

This resource about centering content in CSS is very useful for finding the best solution: https://css-tricks.com/centering-in-the-unknown/

Upvotes: 2

kasijus
kasijus

Reputation: 334

You can add line-height: 36pt to h3 tag.

<div style="background-color: rgb(238, 238, 238); width: 500px; height: 36pt; text-align: center;">
<h3 style="font-family: Helvetica; line-height: 36pt">Hello World!</h3></div>

Upvotes: 2

Related Questions