Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align div with the top of a container

I have an unordered list styled to display horizontally. One of the li elements contains a div element. This div element is filled using ajax, though it shouldn't matter.

The div element has a larger height than the rest of the li elements, and by default it aligns with the bottom of the parent container.

Update: Well, isn't this awkward. I coded a simpler example in jsfiddle http://jsfiddle.net/Bfp3K/, and it works properly. I have to check my code again to get the error in the sandbox.

Update2: It wasn't that easy after all. I have added my proposed (and used) solution.

Update3: Disregard the previous answer, it wasn't correct. This is a simplified and testable example of the problem:

JSFiddle: http://jsfiddle.net/Bfp3K/10/

CSS:

#one {
    background-color:red;
}
#two {
    background-color:green;
}
#three {
    background-color:yellow;
}
#four {
    background-color:blue;
}
.normal {
    height:100px;
    width:200px;
    display:inline-block;

}
.big {
    height:200px;
    width:300px;
    display:inline-block;
}

ul {
    display:block;
}

ul li{
    display:inline;
}

HTML:

<ul>

<li><div id="one" class="normal">One</div></li>
<li><div id="two" class="normal">Two</div></li>
<li><div id="three" class="normal">Three</div></li>
<li><div id="four" class="big">
    The last div vertically aligns to it's content's last line of text. I want to align the top of all the colored divs.

</div></li>
</ul>

Images:

What the solution should look like: Accetable solution What the problem looks like: Current Problem

like image 343
GCon Avatar asked Jun 28 '13 20:06

GCon


4 Answers

The solution was very simple after all. Based on another answer:

li div{
    vertical-align:top;

}

Since the elements have display:inline-block;, adding vertical-align:top seems to solve it. I won't mark this as the solution in case this isn't the proper solution.

http://jsfiddle.net/dv3Mm/

like image 189
GCon Avatar answered Oct 15 '22 17:10

GCon


Just replace the display:inline-block; declarations with float:left; Since you're specifying the dimensions anyway, you don't need inline-block. The jsFiddle works and here's a pic. enter image description here

.normal {
    height:100px;
    width:200px;
    float:left;}

.big {
    height:200px;
    width:300px;
    float:left;}
like image 34
frenchie Avatar answered Oct 15 '22 17:10

frenchie


updated (bottom-aligned):

<html>
<head>
<style>
li {
    display:inline-block;
}
.item {
    vertical-align: bottom; 
}
</style>
</head>
<body>
<ul>
    <li>Text 1</li>
    <li><div class="item">Text 2<img src="some.jpg"/></div></li>
    <li>Text 3</li>
</ul>
</body>
</html>
like image 39
Alex Avatar answered Oct 15 '22 19:10

Alex


Set the LI's line-height to the same pixel height of the image.

like image 37
Rob W Avatar answered Oct 15 '22 18:10

Rob W