Index: media.php
===================================================================
--- media.php	(revision 11953)
+++ media.php	(working copy)
@@ -598,6 +598,7 @@
 }
 
 add_shortcode('gallery', 'gallery_shortcode');
+add_action ( 'template_redirect' , 'gallery_scan' );
 
 /**
  * The Gallery shortcode.
@@ -677,31 +678,13 @@
 
 	$selector = "gallery-{$instance}";
 
-	$output = apply_filters('gallery_style', "
-		<style type='text/css'>
-			#{$selector} {
-				margin: auto;
-			}
-			#{$selector} .gallery-item {
-				float: left;
-				margin-top: 10px;
-				text-align: center;
-				width: {$itemwidth}%;			}
-			#{$selector} img {
-				border: 2px solid #cfcfcf;
-			}
-			#{$selector} .gallery-caption {
-				margin-left: 0;
-			}
-		</style>
-		<!-- see gallery_shortcode() in wp-includes/media.php -->
-		<div id='$selector' class='gallery galleryid-{$id}'>");
+	$output = apply_filters('gallery_style', "<div id='$selector' class='gallery galleryid-{$id}'>");
 
 	$i = 0;
 	foreach ( $attachments as $id => $attachment ) {
 		$link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);
 
-		$output .= "<{$itemtag} class='gallery-item'>";
+		$output .= "<{$itemtag} class='gallery-item' style='width:{$itemwidth}%'>";
 		$output .= "
 			<{$icontag} class='gallery-icon'>
 				$link
@@ -724,6 +707,46 @@
 	return $output;
 }
 
+function gallery_style () { 
+
+$output = apply_filters('gallery_style', "
+<!-- [gallery] shortcode style -->
+<style type='text/css'>
+       .gallery {
+                margin: auto;
+        }
+        .gallery-item {
+                float: left;
+                margin-top: 10px;
+                text-align: center;
+	}
+        .gallery img {
+                border: 2px solid #cfcfcf;
+        }
+        .gallery-caption {
+                margin-left: 0;
+        }
+</style>
+");
+ 
+echo $output;
+}
+
+function gallery_scan () { 
+        global $posts; 
+ 
+        if ( !is_array ( $posts ) ) 
+                return; 
+ 
+        foreach ( $posts as $post ) { 
+                if ( false !== strpos ( $post->post_content, '[gallery' ) ) { 
+                        add_action ( 'wp_head', 'gallery_style' ); 
+                        break; 
+                } 
+        } 
+}
+
+
 /**
  * Display previous image link that has the same post parent.
  *

