WWW FAQs: How do I eliminate the double line break before and after a ul list?


2006-09-21: The <ul> element is the traditional way to present a list of items in HTML, going all the way back to the very first versions of HTML. But the use of <ul> went out of style in the days when cascading style sheets (CSS) was not yet reliable.

Thanks to CSS, <ul> has made a comeback. CSS can be used to radically customize the appearance of lists without introducing ugly markup into the HTML itself. For great examples with complete code, see the excellent listamatic pages on the maxdesign website.

However, there's one very simple and common annoyance with the <ul> element that still comes up: like <p>, <ul> forces a double line break before and after the list. If this works for your design, it's fine. If not, it's a major annoyance. Can this double line break be eliminated?

Yes, you can eliminate the double breaks! It's simple and just requires a little bit of CSS. The secret is to turn off the top and bottom margins for the <ul> element. Here's code for a simple page that takes advantage of CSS to do the job:


<html>
<head>
<title>ul without break demo</title>
<style>
ul {
  margin-top: 0px;
  margin-bottom: 0px;
}
</style>
</head>
<body>
Friendly Pets
<ul>
<li>Cats
<li>Dogs
<li>Piranhas
</ul>
Don't you think piranhas are cuddly?
</body>
</html>

And here's a working example. Notice that there is only a single line break between the list and the text before and after it:

Friendly Pets
  • Cats
  • Dogs
  • Piranhas
Don't you think piranhas are cuddly?
Mission accomplished!

Of course, you should place the style code in a separate CSS file for convenience, readability and easy reuse from all of your web pages. See what is CSS? for an explanation of how to do this.

Legal Note: yes, you may use sample HTML, Javascript, PHP and other code presented above in your own projects. You may not reproduce large portions of the text of the article without our express permission.

Got a LiveJournal account? Keep up with the latest articles in this FAQ by adding our syndicated feed to your friends list!