The best way:
<!doctype html>
<head><title></title></head>
<style type="text/css">
ul {
width: 300px;
}
li {
width: 75px;
margin: 10px;
display: inline-block;
}
</style>
<body>
<ul>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
</ul>
</body>
</html>
The solution is to use inline-block and let the browser determine the proper height for the ul. If you can't use inline-block since you need support for older browsers, let me know and we'll go from there.
The jQuery solution:
<!doctype html>
<head><title></title></head>
<style type="text/css">
ul {
width: 300px;
}
li {
width: 75px;
height: 75px;
margin-top: 10px;
margin-right: 10px;
display: inline-block;
}
</style>
<script src="http://code.jquery.com/jquery-1.4.2.min.js" type="application/javascript"></script>
<script type="application/javascript">
$(document).ready(function() {
var numitems = $("#my_grid li").length;
var numrows = Math.ceil(numitems / 3);
var myheight = (numrows * 75) + (numrows * 10);
$("ul#my_grid").height(myheight);
});
</script>
<body>
<ul id="my_grid">
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
</ul>
</body>
</html>
Note that you need to find the ceiling for numrows, otherwise your height wouldn't be large enough if you have 10 elements, for example.
The jQuery solution comes with a huge caveat:
This will only work if you know exactly how tall each li will be. If you decide at any point that you need to determine the size dynamically (such as in Pjotrovitz's answer), you will need to be careful to make sure that your function does not execute until all stylesheets have been loaded so that the final size of your element can be determined. Otherwise, the JavaScript may determine the height of the element before all styles have been applied and you will get strange results. For that reason, I highly recommend letting the browser and CSS handle all of the layout duties if possible.