Block vs. Inline Elements

From Knowledge Kitchen
Jump to: navigation, search


An understanding of the CSS display property is critical to developing web pages.

Display property

The CSS display property has three basic values:

  • block
  • inline
  • none

Block display elements

Elements with the display property set to "block" share the following features:

  • consume as much width as is available to them
  • don't sit side-by-side with other elements

Common block elements

Some common block elements:

  • div
  • header and footer
  • section and article
  • aside
  • nav
  • h1 - h6
  • p
  • ul and ol
  • li

Inline display elements

Elements with the display property set to "inline" share the following features:

  • consume only as much width as the content inside of them
  • flow side-by-side like text

Common inline elements

Some common inline elements:

  • span
  • a
  • strong
  • em
  • img


None display elements

Elements with the display property set to "none" do not appear on the page at all.


General layout technique

  • Use block elements for major structure of your pages.
  • To get block elements to sit side-by-side:
    • float each element left
    • give each a specific width
    • add an empty div with the clear:both property after the last floating element

Simple example

HTML code:

 <!doctype html>
 <html>
 	<head>
 		<link rel="stylesheet" type="text/css href="css/main.css" />
 		<title>Simple layout</title>
 	</head>
 	<body>
 		<div id="wrapper">
 			<header>
 				Header goes here
 			</header>
 			<section id="left_section">
 				Left section goes here
 			</section>
 			<section id="right_section">
 				Right section goes here
 			</section>
 			<div class="clear"></div><!-- invisible div must be put immediately after any series of elements that are floating, like the sections above -->
 			<footer>
 				Footer goes here
 			</footer>
 		</div>
 	</body>
 </html> 
 

CSS code:

div#wrapper {
    width: 960px; /* fixed page width */
    margin-left: auto; /* set equal left and right margins to center the entire page */
    margin-right: auto;
}
section#left_section {
    width: 320px; /* reduce width */
    float: left; /* make it sit side-by-side with other section */
}
section#right_section {
    width: 640px; /* reduce width */
    float: left; /* make it sit side-by-side with other section */
}
div.clear {
    clear: both; /* makes sure nothing sits to the left or the right of these insvisible divs */
}

More examples

See


What links here