Wednesday, April 11, 2012

I am trying to align three elements, on the left, the right, and the center. Center element = dynamic width, containing element = width of browser

Here is what I am trying to do: I have a <h1> element, a <time> element, and a <div>, all within a <header> that is the full width of the browser window. The <h1> element needs to be on the left, the <time> element, which changes width with the time, needs to be centered, and the <div> needs to be on the right.


I have been trying to work this out for a while but haven't had any luck. Perhaps it requires some javascript? I also need to be able to (I think using absolute positioning?) vertically center align them all, and they are all different font sizes.


Heres the HTML so far:


<header>
     <h1>blahblah.com</h1>
     <time>THE TIME</time>
     <div id="controls">
         DISPLAY CONTROLS
     </div>
 </header>
 


and the CSS:


* {
     margin: 0px;
     padding: 0px;
 }
 header {
     background: black;
     color: white;
     width: 100%;
     font-family: wendy;
 }
 header h1 {
     display: inline-block;
     font-size: 40px;
     margin-left: 10px;
 }
 header time {
     font-size: 30px;
 }
 header #controls {
     display: inline-block;
 }
 #controls p {
     display: inline-block;
     font-size: 20px;
 }
 


Thank you very much!


Answer:


Time is an inline element, so text-align: center for the header is enough to get the time centered. Further, get rid of those unnecessary inline-block styles.
And then the base aligning style sheet shrinks to this fiddle example:
header { 
    width: 100%; 
    overflow: hidden;
    text-align: center;
} 
header h1 { 
    float: left;
} 
header #controls { 
    float: right;    } 
Overflow is added to assure extending the height of the header to that of the floated elements , whichever is tallest.

No comments:

Post a Comment