Monday, April 7, 2014

CSS how to due a simple header!

CSS is a PITA. Even doing something simple can be difficult. Here is some things I have done in the past to make a simple header work.

<div class="header">
    <span class="left"> Left </span>
    <span class="right">Right</span>
</div>

My first version is a simple way to start out. You make the header absolute and use floats to put the pieces in place.

.header {
    position: absolute;
    top: 0px;
    left: 0px;
    right: 0px;
    height: 50px;
}
.header .left {
    float: left;
}
.header .right {
    float: right;
}

I do that it does the right thing. I am happy and I keep going. Then it is discovered that when the contents of left and right get long they start wrapping and wrap right out of the header! It looks horribly broken! So I switch gears. I use absolute to position things on the right and left.

.header .left {
    position: absolute;
    left: 0px;
}
.header .right {
    position: absolute;
    right: 0px;
}

Okay, now things don't wrap so nothing in the header escapes the header. But when things are too long they start overlapping. It looks bad! (Although not as bad as the first way, although this way is less readable because you have overlaps.) So to kill the overlap we do the following:

.header .left {
    position: absolute;
    left: 0px;
    z-index: 1;
    background: inherit;
    padding-right: 5px;
}

This places the stuff on the left over the stuff on the right so you never see overlapping text. The right text simply slides under the left text.

Okay, so they can still wrap out of the header area. So you add height and overflow properties to the left and right sections.

.header .left {
    height: 50px;
    overflow: hidden;
}
.header .right {
    height: 50px;
    overflow: hidden;
}

So all together you have:

.header {
    position: absolute;
    top: 0px;
    left: 0px;
    right: 0px;
    height: 50px;
}
.header .left {
    position: absolute;
    left: 0px;
    z-index: 1;
    background: inherit;
    padding-right: 5px;
    height: 50px;
    overflow: hidden;
}
.header .right {
    position: absolute;
    right: 0px;
    height: 50px;
    overflow: hidden;
}

So this is ignoring "Responsive Web Design" where you change what is in the header dynamically based on the size of the screen allowing a better experience for multiple form factors. But you know what, that is harder and sometimes the easy solution makes sense.

No comments:

Post a Comment