user6161942
user6161942

Reputation:

H1 won't center with a set width

I am trying to center an h1 tag, but it doesn't work when I set it's width. When I don't set a specific width it works, but I would like to keep the width at 400. My code is below.

body {
    margin: 0;
    font-family: Arial;
    font-size: 1em;
}

.navbar-ul {
    margin: 0;
    color: white;
    background-color: black;
    overflow: hidden;
    -webkit-box-shadow: -1px 10px 20px 0px rgba(0,0,0,0.75);
    -moz-box-shadow: -1px 10px 20px 0px rgba(0,0,0,0.75);
    box-shadow: -1px 10px 20px 0px rgba(0,0,0,0.75);
}

a {
    color: white;
}

li, a {
    text-decoration: none;
    display: inline-block;
    padding: 10px;
    background-color: black;
    transition: 1s;
    border: solid 1px transparent;
}

li:hover, li:hover a {
    background-color: #3f3f3f;
}

.header-text {
    border: solid 5px black;
    width: 400px;
    text-align: center;
    padding: 25px;
}

li {
    list-style-type: none;
    float: left;
}
<!DOCTYPE html>
<html>
    
    <head>
        <meta charset="utf-8">
        <title>Dark Website Template by Jordan Baron</title>
        <link rel="stylesheet" href="styles-main.css">
    </head>
    
    <body>
        <div class="navbar">
            <ul class="navbar-ul">
                <strong><li><a href="#">HOME</a></li>
                <li><a href="#">CONTACT</a></li>
                <li><a href="#">ABOUT</a></li></strong>
            </ul>
        </div>
        <strong><h1 class="header-text">DARK</h1></strong>
        
    </body>
    
</html>

I don't think the other elements are the problem, but hey, it's a possibility.

Upvotes: 3

Views: 1696

Answers (2)

Duncan Lukkenaer
Duncan Lukkenaer

Reputation: 13914

The h1-element is a block-element. This means that the width is 100% by default. By using text-align: center you only center the text inside the element, not the h1 itself.

When you set the width to 400px the text is still centered inside the block, but the element itself no longer has a full-width.

The solution would be to center the element as a whole. This can be done by setting the horizontal margin to auto.

This should work for you:

.header-text {
  border: solid 5px black;
  width: 400px;
  text-align: center;
  padding: 25px;
  margin: 0 auto;
}
<h1 class="header-text">DARK</h1>

For more information about centering with CSS, check out this guide: https://css-tricks.com/centering-css-complete-guide/

Upvotes: 2

Turi S.
Turi S.

Reputation: 331

If you're trying to center the entire element, you can use the auto value for the left and right margin on the header:

.header-text {
   margin: 0 auto;
}

Upvotes: 1

Related Questions