Search code examples
htmlcssheadercenter

How to place a header on top of centered div? (html/css)


I'm new at coding and I've managed to figure out some things, but this one is bugging me deeply as I can't seem to find a solution.

I have an horizontal & vertically centered div on a page. I want to place a header on top of it, without decentering the main div.

How it looks like now (both are centered as a whole): both are centered as a whole.

How I want it to look (yellow is centered, blue header on top): yellow is centered, blue header on top.

.. Basic code:

.outer {
  display: table;
  position: absolute;
  height: 100%;
  width: 100%;
}
.middle {
  display: table-cell;
  vertical-align: middle;
}
.header {
  width: 1000px;
  height: 100px;
  background-color: blue;
  margin-left: auto;
  margin-right: auto;
}
.main {
  width: 1000px;
  height: 500px;
  background-color: yellow;
  margin-left: auto;
  margin-right: auto;
}
<div class="outer">
  <div class="middle">
    <div class="header"></div>
    <div class="main">
    </div>
  </div>
</div>


Solution

  • This is most likely not the best answer, but it's a start. Baisically I centered the container using this method. Then I added the -50px to the top attribute of the container (half of the header height), moving the container 50px upwards, making the content div totally centered again. This solution should work on most newer browsers, but has some "limits" more here.

    HTML

    <div class="centered-container">
        <div class="header">
            header stuff
        </div>
        <div class="content">
            Content stuff here.
      </div>
    </div>
    

    CSS

    body {
      background: #600;
    }
    
    .centered-container {
      position: absolute;
      left: 50%;
      top: 50%;
      top: calc(50% - 50px);
      transform: translate(-50%, -50%);
      width: 600px;
      background: red;
      color: white;
      text-align: center;
    }
    
    .header {
        height:100px;
        background:blue;
    }
    
    .content {
        height:300px;
        background:teal;
    }
    

    fiddle here.

    I made the content 600px wide and 300px high and header 100px high, just so it is easier to see. The negative margin