Home > Enterprise >  Why I can put header to the center. But can't put header child to the center?
Why I can put header to the center. But can't put header child to the center?

Time:11-05

I have this HTML Code:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <title>Test Project</title>
</head>
<body>
    <header>
        <h1>MarioClub</h1>
    </header>
</body>
</html>

With this css module:

header {
    text-align: center;
    position: fixed;
    width: 100%;
    color: black;
    background: yellow;
    border-width: medium;
    border-color: black;
    z-index: 1;
    top: 0;
    left: 0;
}

header h1 {
    /*text-align: center;*/
    padding: 10px 10px;
    border: 8px solid black;
    display: inline-block;
}

When I put "text-align: center;" into the "header" selector, It work as well. But when I remove it from header, and add to "header h1" selector, text-align does not work. Why it's not work?

I think it have to work conversely, because I want to put "h1"s text to the center, but not all "headers" text.

It work like this when I put text-aling to the "header" selector It work like this when I put text-aling to the "header" selector

And like this when I put it into "header h1" selector And like this when I put it into "header h1" selector

CodePudding user response:

Putting text-align on the h1 only aligns the text inside it, not itself. Putting text-align on the header aligns all of the header's children.

CodePudding user response:

Because inline-block doesn't get full parent width, so, althought its text is centered, it doesn't seem that. Just inspect h1 element with your browser inspector, and see the difference in both cases.

CodePudding user response:

According to the definition of property in: https://www.w3schools.com/cssref/pr_text_text-align.ASP

"The text-align property specifies the horizontal alignment of text in an element."

Inside the element, since the h1 is the children of the header, when you specify the property for header centers the h1 this also happens because of inline-block (that changes the default behaviour) otherwise the h1 expands to all available horizontal space, so the border will span all the page.

  • Related