Search code examples
htmlcssalignment

centering website using header tag


I want to know if it is possible to center a website header which has not been placed into divisions, but has been placed in the header tag.

It's code goes something like this:

 <header>
    <div class="top">
    </div>
    <div class="image">
    </div>
    </header>

The CSS goes something like this:

header
{
width: 100%;
margin: 0 auto;
}

.top
{
width: 30%;
background: yellow;
float:left;
padding: 2.5%
}

.image
{
width: 45%;
background: black;
float: left;
}

I want the contents inside the header to be centered in origanal size as well as when the website is being used in a smaller resolution (i.e. mobile).

How do I go about doing this?


Solution

  • Use display: inline-block instead of float: left.

    The elements will then be inline. When adding a text-align: center to the header will make them center inside it.

    header {
      width: 100%;
      text-align: center;
    }
    .top, .image {
      display: inline-block;
      vertical-align: top;
      margin-left: -4px;
    }
    .top {
      width: 30%;
      background: yellow;
      padding: 2.5%
    }
    .image {
      width: 45%;
      background: black;
    }
    <header>
      <div class="top">t</div>
      <div class="image">i</div>
    </header>