Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: aligning elements inside a div

I have a div that contains three elements, and I am having problems correctly positioning the last one. The div at the left has to be at the left, the one in the middle needs to be centered, and the third one needs to be to the right.

So, I have something like:

#left-element {
    margin-left: 9px;
    margin-top: 3px;
    float:left;
    width: 13px;
}

#middle-element {
    margin:0 auto;
    text-align: center;
    width: 300px;
}

#right-element {
    float:right;
    width: 100px;
}

My html looks like this:

   <div id="container-div">
        <div id="left-element">
            <img src="images/left_element.png" alt="left"/>
        </div>
        <div id="middle-element">
            I am the text inside the middle element
        </div>
        <div id="right-element">
            I am the text in right element
        </div>
    </div>

Any ideas?

Thanks!

like image 259
luqita Avatar asked Apr 30 '11 13:04

luqita


1 Answers

You haven't included css for your container div, but whenever it contains floating elements you should hide overflow like so:

#container {
  overflow: hidden;
  width: 100%; /* for good measure */
}

When you position the middle div you are setting margins that span the entire container, so any further elements are getting positioned on the line below. Note, at least for most modern browsers, further. If you reorder your elements, like so:

<div id="container">
    <div id="left-element">
        <img src="images/left_element.png" alt="left"/>
    </div>
    <div id="right-element">
        I am the text in right element
    </div>
    <div id="middle-element">
        I am the text inside the middle element
    </div>
</div>

You should find it works. Better method, as I'm not quite sure whether that is supposed to work, would be to use css positioning. Apply the following css:

#container {
  overflow: hidden;
  width: 100%;
  min-height: 36px; /* Remember absolute positioning is outside the page flow! */
  position: relative;
}
#left-element {
  position: absolute;
  left: 9px;
  top: 3px;
  width: 13px;
}
#middle-element {
  margin: 0 auto;
  text-align: center;
  width: 300px;
}
#right-element {
  position: absolute;
  right: 0px;
  top: 0px;
  width: 100px;
}
like image 162
lpd Avatar answered Oct 02 '22 14:10

lpd