Home > Net >  text-align in <body> not applying to a nested class?
text-align in <body> not applying to a nested class?

Time:10-05

My prime objective was to create webpage with a heading with a border, and text underneath it which is as wide as the border of the heading (so if the heading with the border is 500px, then the text underneath should be directly underneath it, ie have a width of 500px).

I have used text-align: center; in the body tag already, so as to align the heading of the webpage to the center. I assumed everything written in the body tag would be centered automatically since they are all nested in body.

Inside the body, for the actual text written in the page, I've used a <div class="content"> container. I know that it has been applied satisfactorily to the actual text because all other formatting applies onto it as expected.

However, when I write width: 500px; inside the .content{}, the text suddenly goes into a left alignment. I tried to use text-align: center; in the .content{} class too, but even that didn't align the text in the center.

What am I missing here? Why isn't the actual text being displayed in the center, directly underneath the heading?

Thanks in advance!

CodePudding user response:

For div tag when you set a width you also need to say that the div is no more block but inline-block elsewhere it becomes a block with the specified width. So one of these solutions works:

.content{
    width:500px;
    display:inline-block;
}

or

.content{
    width:500px;
    margin:auto;
}

CodePudding user response:

You have given the div a specific width in pixels. To make sure it is centred within your page you should apply a margin:0 auto css rule to it so that it will automatically calculate the side margins to center the element.

Be aware that the margin:0 auto technique does not always work. Here are the rules for it to work:

  1. The element must be block-level, e.g. display: block or display: table
  2. The element must not float
  3. The element must not have a fixed or absolute position
  4. The element must not have auto as width value
  • Related