<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>TutWow &#187; HTML/CSS</title>
	<atom:link href="http://www.tutwow.com/category/htmlcss/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.tutwow.com</link>
	<description>Playing Creativity Tag</description>
	<lastBuildDate>Mon, 30 Jan 2012 17:48:27 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Create a Simple and Secure Contact Form with jQuery and PHP</title>
		<link>http://www.tutwow.com/htmlcss/create-a-simple-and-secure-contact-form-with-jquery-and-php/</link>
		<comments>http://www.tutwow.com/htmlcss/create-a-simple-and-secure-contact-form-with-jquery-and-php/#comments</comments>
		<pubDate>Sat, 21 Jan 2012 20:45:55 +0000</pubDate>
		<dc:creator>Ben Lind</dc:creator>
				<category><![CDATA[HTML/CSS]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.tutwow.com/?p=1375</guid>
		<description><![CDATA[In this tutorial, we walk through the steps needed to create a simple and secure contact form with HTML, CSS, Javascript, and PHP.]]></description>
			<content:encoded><![CDATA[<p>Today we will be creating a simple yet secure contact form with PHP and Javascript. I have used this contact form on multiple websites, and I find it to be very easy to use and install, so you should enjoy it.</p>
<h2><a href="http://img.tutwow.com/simplesecurecontact/contact.html">See the final result in action.</a></h2>
<h2><a href="http://www.tutwow.com/wp-content/uploads/2012/01/SimpleSecureContactForm-TutWow.zip">Download the files for this tutorial.</a></h2>
<h1>Step 1 &#8211; Download the Files</h1>
<p>Before we get started, go download the following javascript files:</p>
<ol>
<li>The <a href="http://code.jquery.com/jquery.min.js">latest minified version</a> of jQuery</li>
<li>The <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/">jQuery Validate plugin</a> (click the Download link on the page, unzip the downloaded file, and then copy out the <strong>jquery.validate.js</strong> file)</li>
<li>The <a href="http://malsup.github.com/jquery.form.js">jQuery Form plugin</a></li>
</ol>
<p>After you have downloaded those three files, place them in a folder named <strong>js</strong> in the directory where you want to have your contact form. Now you&#8217;re ready to start crafting the contact form!</p>
<h1>Step 2 &#8211; HTML</h1>
<p>First off, make sure that you have a basic understanding of HTML, PHP, and Javascript. <a href="http://w3schools.com/">W3schools.com</a> is a great resource for quickly getting up to speed with these languages. Once you have a grip of these technologies, you should be able to understand what is going on in this tutorial much better.</p>
<p>To start off, create a new file on your server named <strong>contact.html</strong>. It can be named whatever you want (or you can add the contact form to an existing file), but for the sake of this tutorial we will use contact.html.</p>
<p>In this file, add the following code:</p>
<pre class="brush: html; gutter: true">&lt;!DOCTYPE HTML&gt;
&lt;html&gt;
	&lt;head&gt;
		&lt;title&gt;Contact Form&lt;/title&gt;

		&lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot; type=&quot;text/css&quot; /&gt;

		&lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery.min.js&quot;&gt;&lt;/script&gt;
		&lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery.validate.min.js&quot;&gt;&lt;/script&gt;
		&lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery.form.js&quot;&gt;&lt;/script&gt;
		&lt;script type=&quot;text/javascript&quot; src=&quot;js/contact.js&quot;&gt;&lt;/script&gt;
	&lt;/head&gt;
	&lt;body&gt;
		&lt;div id=&quot;wrap&quot;&gt;
			&lt;h1&gt;Contact Sweetness&lt;/h1&gt;
			&lt;form id=&quot;contactform&quot; action=&quot;processForm.php&quot; method=&quot;post&quot;&gt;
				&lt;table&gt;
					&lt;tr&gt;
						&lt;td&gt;&lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;&lt;/td&gt;
						&lt;td&gt;&lt;input type=&quot;text&quot; id=&quot;name&quot; name=&quot;name&quot; /&gt;&lt;/td&gt;
					&lt;/tr&gt;
					&lt;tr&gt;
						&lt;td&gt;&lt;label for=&quot;email&quot;&gt;Email:&lt;/label&gt;&lt;/td&gt;
						&lt;td&gt;&lt;input type=&quot;text&quot; id=&quot;email&quot; name=&quot;email&quot; /&gt;&lt;/td&gt;
					&lt;/tr&gt;
					&lt;tr&gt;
						&lt;td&gt;&lt;label for=&quot;message&quot;&gt;Message:&lt;/label&gt;&lt;/td&gt;
						&lt;td&gt;&lt;textarea id=&quot;message&quot; name=&quot;message&quot; rows=&quot;5&quot; cols=&quot;20&quot;&gt;&lt;/textarea&gt;&lt;/td&gt;
					&lt;/tr&gt;
					&lt;tr&gt;
						&lt;td&gt;&lt;/td&gt;
						&lt;td&gt;&lt;input type=&quot;submit&quot; value=&quot;Send!&quot; id=&quot;send&quot; /&gt;&lt;/td&gt;
					&lt;/tr&gt;
				&lt;/table&gt;
			&lt;/form&gt;
			&lt;div id=&quot;response&quot;&gt;&lt;/div&gt;
		&lt;/div&gt;
	&lt;/body&gt;
&lt;/html&gt;</pre>
<p>This code contains the structure for our contact form. Let&#8217;s take a look at what each section is doing.</p>
<pre class="brush: html; gutter: true;">&lt;!DOCTYPE HTML&gt;
&lt;html&gt;
	&lt;head&gt;
		&lt;title&gt;Contact Form&lt;/title&gt;</pre>
<p>These lines set up the basic structure of the HTML document, and they should be second nature to you.</p>
<pre class="brush: html; gutter: true; first-line: 6;">		&lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot; type=&quot;text/css&quot; /&gt;

		&lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery.min.js&quot;&gt;&lt;/script&gt;
		&lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery.validate.min.js&quot;&gt;&lt;/script&gt;
		&lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery.form.js&quot;&gt;&lt;/script&gt;
		&lt;script type=&quot;text/javascript&quot; src=&quot;js/contact.js&quot;&gt;&lt;/script&gt;</pre>
<p>First we include the CSS stylesheet that we will be creating shortly, and then we proceed to include all three of the javascript files that we just downloaded into the js folder. The last line is including &lt;strong&gt;contact.js&lt;/strong&gt;, a file we will create later on.</p>
<pre class="brush: html; gutter: true; first-line: 12">	&lt;/head&gt;
	&lt;body&gt;
		&lt;div id=&quot;wrap&quot;&gt;
			&lt;h1&gt;Contact Sweetness&lt;/h1&gt;
			&lt;form id=&quot;contactform&quot; action=&quot;processForm.php&quot; method=&quot;post&quot;&gt;</pre>
<p>This ends the head and starts the body of the page. We set up a &#8220;wrap&#8221; div that will be used to style the contact form with CSS later on, and add a heading at the top of the new div. Then we start the form that will contain all of the inputs where the user will type in their info and message. The action of the form is set to <strong>processForm.php</strong>, another file which we will create later on. The reason we add this file to the action attribute of the form instead of just doing all of the processing with javascript is that someone without javascript enabled will be able to use the form as well as someone with javascript enabled. The key here is <em>progressive enhancement</em>, or making sure that users with less capabilities will still be able to use your website. Always start by coding for the lowest common denominator &#8211; users who don&#8217;t have javascript in this case &#8211; and then adding better functionality for users with better browsers/more capable systems.</p>
<pre class="brush: html; gutter: true; first-line: 17">				&lt;table&gt;
					&lt;tr&gt;
						&lt;td&gt;&lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;&lt;/td&gt;
						&lt;td&gt;&lt;input type=&quot;text&quot; id=&quot;name&quot; name=&quot;name&quot; /&gt;&lt;/td&gt;
					&lt;/tr&gt;
					&lt;tr&gt;
						&lt;td&gt;&lt;label for=&quot;email&quot;&gt;Email:&lt;/label&gt;&lt;/td&gt;
						&lt;td&gt;&lt;input type=&quot;text&quot; id=&quot;email&quot; name=&quot;email&quot; /&gt;&lt;/td&gt;
					&lt;/tr&gt;
					&lt;tr&gt;
						&lt;td&gt;&lt;label for=&quot;message&quot;&gt;Message:&lt;/label&gt;&lt;/td&gt;
						&lt;td&gt;&lt;textarea id=&quot;message&quot; name=&quot;message&quot; rows=&quot;5&quot; cols=&quot;20&quot;&gt;&lt;/textarea&gt;&lt;/td&gt;
					&lt;/tr&gt;
					&lt;tr&gt;
						&lt;td&gt;&lt;/td&gt;
						&lt;td&gt;&lt;input type=&quot;submit&quot; value=&quot;Send!&quot; id=&quot;send&quot; /&gt;&lt;/td&gt;
					&lt;/tr&gt;
				&lt;/table&gt;</pre>
<p>These lines contain the actual input areas for the contact form. As you can see, I am using a table to format the form, even though tables are typically frowned upon in the design community. I find that in certain situations, when I want to easily align different elements in nice grids, tables are just the easiest option, but you can of course use divs if that&#8217;s what you prefer. Each input element has both an id and a name which are needed for processing the input with javascript and PHP and for styling the form with CSS. We&#8217;ll see how all of these values work together soon.</p>
<pre class="brush: html; gutter: true; first-line: 35">			&lt;/form&gt;
			&lt;div id=&quot;response&quot;&gt;&lt;/div&gt;
		&lt;/div&gt;
	&lt;/body&gt;
&lt;/html&gt;</pre>
<p>Here we are basically just closing all of the tags that we opened up above. However, line 36 contains a new &#8220;response&#8221; div that will contain the response of the processForm.php file when we try to submit a message to it. Again, you will see how this comes into play soon.</p>
<p>Now that you have this basic HTML structure, you should see something like this when you open up contact.html in your browser:</p>
<p><img class="aligncenter size-full wp-image-1399" title="BasicHTML" src="http://www.tutwow.com/wp-content/uploads/2012/01/BasicHTML.jpg" alt="" width="270" height="240" /></p>
<p>It&#8217;s not too pretty yet, but that&#8217;s where the next step comes in&#8230;</p>
<h1>Step 3 &#8211; CSS</h1>
<p>I always love it when I get to the CSS portion of my designing. There&#8217;s something about taking an ugly and deformed hunk of content and crafting it to beautiful pixel perfection that just sets my heart to racing. Okay, that might be going a bit far, but that&#8217;s not really all that far off.</p>
<p>Start by creating a new file next to contact.html named <strong>style.css</strong>. Remember that line in the head of contact.html where we included style.css? Yup, this is the very same one. What a funny coincidence. Anyway, in this new css file, put in this code:</p>
<pre class="brush: css; gutter: true">body {
	background: #24333d;
	color: #4a606f;
	font: 21px &#039;Helvetica&#039;, &#039;Arial&#039;, sans-serif;
	margin: 0;
	padding: 50px 0 0;
}

h1 {
	color: #24333c;
	font-size: 48px;
	font-weight: normal;
	margin: 25px 0 15px;
	text-align: center;
}

#wrap {
	background: #eaf0f4;
	border: 5px solid #7a91a1;
	margin: auto;
	width: 500px;
}

form {
	padding: 0;
	margin: 0 0 20px;
}
table {
	margin: 0 auto;
}
tr, td, input, textarea {
	margin: 0;
	padding: 0;
}
td {
	padding: 0 0 5px;
}
tr td:first-child {
	padding-right: 10px;
	padding-top: 11px;
	text-align: right;
	vertical-align: top;
}
.error[generated=true] {
	color: #dc0000;
	font-size: 16px;
	padding: 5px 0 2px 5px;
}
tr.error td {
	padding: 0;
}
input, textarea {
	background: #FFF;
	border: 3px solid #7a91a1;
	font: inherit;
	font-size: 16px;
	line-height: 29px;
	min-height: 30px;
	padding: 5px 10px;
	width: 300px;
}
input:focus, textarea:focus {
	border-color: #b0c3d0;
	outline: none;
}
textarea {
	height: 240px;
	resize: vertical;
}
input[type=submit] {
	background: #24333d;
	color: #FFF;
	font: inherit;
	padding: 7px 20px;
	width: auto;
}

#response {
	margin-bottom: 20px;
	text-align: center;
}
#response .success {
	color: #08a300;
}
#response .failure {
	color: #dc0000;
}</pre>
<p>Now I could go through each selector and tell you exactly what everything in here does, but that would ruin the fun of you figuring it out yourself (plus it would take a long time for me to write and for you to read, which would be boring for everyone). So take a look at it yourself and see if you can figure out everything that&#8217;s going on. If you run into something you don&#8217;t understand, there&#8217;s this <a href="http://lmgtfy.com/?q=Help!+I+can%27t+figure+out+what+this+code+does!">amazing tool</a> that can help you with basically every aspect of coding that you should <a href="http://lmgtfy.com/?q=Help!+I+can%27t+figure+out+what+this+code+does!">take a look at</a>. It&#8217;s a lifesaver and you should learn to use it if you ever want to get anywhere with your web design.</p>
<p>Some of the things in that CSS have to do with errors and responses, and you probably don&#8217;t know what those mean yet. Don&#8217;t fret, my friend, for soon you will be an expert on errors and responses &#8211; just as soon as we take a look at the javascript portion of this contact form. Now you should have something that looks like this if you refresh contact.html:</p>
<p><a href="http://www.tutwow.com/wp-content/uploads/2012/01/Stylish.jpg" rel="lightbox[1375]"><img class="aligncenter size-large wp-image-1403" title="Styled Up" src="http://www.tutwow.com/wp-content/uploads/2012/01/Stylish-540x579.jpg" alt="" width="540" height="579" /></a></p>
<p>Not too bad!</p>
<h1>Step 4 – Javascript</h1>
<p>Now we get to the fun part – making everything actually work (to some extent)! More specifically, by adding javascript to this contact form, we will be adding validation (making sure the user enters acceptable things into the different fields) and ajax in a nice blend of usefulness. You’ll see what I mean soon enough.</p>
<p>Remember when we referenced contact.js in the HTML file? That’s right, now it’s time to create it! Here we go: inside the js folder that you created in step 1, create a new file and name it <strong>contact.js</strong>. This will hold all of our jQuery goodness. More specifically, it will look like this:</p>
<pre class="brush: javascript; gutter: true; first-line: 1">$(function() {
	// Validate the contact form
  $(&#039;#contactform&#039;).validate({
  	// Specify what the errors should look like
  	// when they are dynamically added to the form
  	errorElement: &quot;label&quot;,
  	wrapper: &quot;td&quot;,
  	errorPlacement: function(error, element) {
  		error.insertBefore( element.parent().parent() );
  		error.wrap(&quot;&lt;tr class=&#039;error&#039;&gt;&lt;/tr&gt;&quot;);
  		$(&quot;&lt;td&gt;&lt;/td&gt;&quot;).insertBefore(error);
  	},

  	// Add requirements to each of the fields
  	rules: {
  		name: {
  			required: true,
  			minlength: 2
  		},
  		email: {
  			required: true,
  			email: true
  		},
  		message: {
  			required: true,
  			minlength: 10
  		}
  	},

  	// Specify what error messages to display
  	// when the user does something horrid
  	messages: {
  		name: {
  			required: &quot;Please enter your name.&quot;,
  			minlength: jQuery.format(&quot;At least {0} characters required.&quot;)
  		},
  		email: {
  			required: &quot;Please enter your email.&quot;,
  			email: &quot;Please enter a valid email.&quot;
  		},
  		message: {
  			required: &quot;Please enter a message.&quot;,
  			minlength: jQuery.format(&quot;At least {0} characters required.&quot;)
  		}
  	},

  	// Use Ajax to send everything to processForm.php
  	submitHandler: function(form) {
  		$(&quot;#send&quot;).attr(&quot;value&quot;, &quot;Sending...&quot;);
  		$(form).ajaxSubmit({
  			target: &quot;#response&quot;,
  			success: function(responseText, statusText, xhr, $form) {
  				$(form).slideUp(&quot;fast&quot;);
  				$(&quot;#response&quot;).html(responseText).hide().slideDown(&quot;fast&quot;);
  			}
  		});
  		return false;
  	}
  });
});</pre>
<p>Yes, that&#8217;s a lot of code to wade through. Let&#8217;s get into it.</p>
<pre class="brush: javascript; gutter: true">$(function() {</pre>
<p>If you have used jQuery before, this should look very familiar. This is jQuery&#8217;s way of waiting until the page is loaded to execute something. Anything inside the function&#8217;s curly brackets will run as soon as the page has finished loading.</p>
<pre class="brush: javascript; gutter: true; first-line: 2">// Validate the contact form
  $(&#039;#contactform&#039;).validate({</pre>
<p>This is telling the Validate plugin that we downloaded and included earlier to validate the #contactform form. By using a plugin instead of validating everything ourselves, everything is just easier for everyone.</p>
<pre class="brush: javascript; gutter: true; first-line: 4">// Specify what the errors should look like
  	// when they are dynamically added to the form
  	errorElement: &quot;label&quot;,
  	wrapper: &quot;td&quot;,
  	errorPlacement: function(error, element) {
  		error.insertBefore( element.parent().parent() );
  		error.wrap(&quot;&lt;tr class=&#039;error&#039;&gt;&lt;/tr&gt;&quot;);
  		$(&quot;&lt;td&gt;&lt;/td&gt;&quot;).insertBefore(error);
  	},</pre>
<p>Though the validate() function works great without any help, we need to give it some extra info so that it will display everything nicely. These first few options deal with where we should display errors when the user types in something they shouldn&#8217;t. You can read about all of the possible options on <a href="http://docs.jquery.com/Plugins/Validation/validate#toptions">this page</a>.</p>
<p>Here&#8217;s what the different arguments do:</p>
<ul>
<li><strong>errorElement</strong>: What element the error message will be placed in. The reason I chose to put it in a label is so that if the user clicks on the error, it will automatically focus the correct text box for them.</li>
<li><strong>wrapper</strong>: Basically like errorElement &#8211; it wraps the error, including the label, in a td tag.</li>
<li><strong>errorPlacement</strong>: A function that specifies where the error should be placed after it is generated. It looks complicated, but really all we are doing is putting it in a tr element next to the tr that the input box is in, and adding an empty td tag before the error to push the error to the right. You&#8217;ll see what I mean if you take a look at the code of the page after an error is generated.</li>
</ul>
<pre class="brush: javascript; gutter: true; first-line: 14">  	// Add requirements to each of the fields
  	rules: {
  		name: {
  			required: true,
  			minlength: 2
  		},
  		email: {
  			required: true,
  			email: true
  		},
  		message: {
  			required: true,
  			minlength: 10
  		}
  	},</pre>
<p>The rules option specifies the details of each input element in the contact form. As you can see, every one of the inputs is required, and the name and message text boxes have minimum amounts of characters allowed. The email text box has a special parameter which tells the Validate plugin that it is an email element. This ensures that any email entered into the form will truly be an email and not just something like &#8220;asdf.&#8221;</p>
<pre class="brush: javascript; gutter: true; first-line: 30">  	// Specify what error messages to display
  	// when the user does something horrid
  	messages: {
  		name: {
  			required: &quot;Please enter your name.&quot;,
  			minlength: jQuery.format(&quot;At least {0} characters required.&quot;)
  		},
  		email: {
  			required: &quot;Please enter your email.&quot;,
  			email: &quot;Please enter a valid email.&quot;
  		},
  		message: {
  			required: &quot;Please enter a message.&quot;,
  			minlength: jQuery.format(&quot;At least {0} characters required.&quot;)
  		}
  	},</pre>
<p>As you can see, this messages option looks suspiciously like the rules option we just looked at. The reason for this is that in this option we specify what error messages to show the user when they break one of the rules we just set up. For example, if the name that they enter doesn&#8217;t meet the minimum length requirement, it will say &#8220;At least 2 characters required.&#8221;</p>
<pre class="brush: javascript; gutter: true; first-line: 47">  	// Use Ajax to send everything to processForm.php
  	submitHandler: function(form) {</pre>
<p>This line of code is yet another option that we&#8217;re passing the Validate plugin, this time specifying what should happen when the form is submitted (with no errors). Let&#8217;s take a look at what&#8217;s going to happen when the Send button is clicked:</p>
<pre class="brush: javascript; gutter: true; first-line: 49">$(&quot;#send&quot;).attr(&quot;value&quot;, &quot;Sending...&quot;);</pre>
<p>So when the form is submitted, we begin by changing the text in the submit button from &#8220;Send!&#8221; to &#8220;Sending&#8230;.&#8221; The reason for this is that the Ajax server request takes a few seconds, so we want to make sure that the user knows something&#8217;s going on.</p>
<pre class="brush: javascript; gutter: true; first-line: 50">  		$(form).ajaxSubmit({
  			success: function(responseText, statusText, xhr, $form) {
  				$(form).slideUp(&quot;fast&quot;);
  				$(&quot;#response&quot;).html(responseText).hide().slideDown(&quot;fast&quot;);
  			}
  		});</pre>
<p>The cool thing about this form is that it doesn&#8217;t reload the page when the Send button is pressed, it just sends the email asynchronously (in the background). It&#8217;s called using Ajax, and it&#8217;s pretty nifty. These lines of code use the other plugin we downloaded at the start &#8211; the Form plugin &#8211; to do all the Ajax kungfooery. We pass just one parameter to the ajaxSubmit function: <strong>success</strong>. This tells the form what to do when the form is submitted successfully. In there we tell the entire form to hide itself by sliding up, and we then insert the response text into the #response div.</p>
<p>Here&#8217;s how it works: The user fills in the form and hits the send button, and the content is sent to processForm.php to be emailed. If there are no errors with the sending of the email and it is sent successfully, the processForm file sends back a message to contact.html saying &#8220;Success!&#8221; However, if there is an error along the way, it sends back a &#8220;Failed!&#8221; message. This message (either success or failure) is then put into the #response div.</p>
<p>That&#8217;s it for the javascript! Now the form should validate correctly, and if you type in some bogus information, it will give you pretty errors like this:</p>
<p><a href="http://www.tutwow.com/wp-content/uploads/2012/01/Errors.jpg" rel="lightbox[1375]"><img class="alignnone size-large wp-image-1422" title="Errors" src="http://www.tutwow.com/wp-content/uploads/2012/01/Errors-540x656.jpg" alt="" width="540" height="656" /></a></p>
<h1>Step 5 – PHP</h1>
<p>We&#8217;re onto the final section of our little contact form &#8211; PHP! The purpose of the PHP is first off to actually send the message that the user typed into the form, and secondly to do some additional error validation. Why do we need to do more validation, you ask? Why can&#8217;t we just rely on the javascript to catch everything? Well, think about what would happen if the user doesn&#8217;t have javascript enabled when they submit the form – no errors will occur! All of their data, including anything that might be erroneous, will be emailed to you, and that&#8217;s not what you want. So we&#8217;re forced to repeat all of the validating that we did before in javascript, this time in PHP. Here we go!</p>
<p>Create another file &#8211; the final file &#8211; and name it <strong>processForm.php</strong>. In it, put the following code:</p>
<pre class="brush: php; gutter: true">&lt;?php

// Clean up the input values
foreach($_POST as $key =&gt; $value) {
	if(ini_get(&#039;magic_quotes_gpc&#039;))
		$_POST[$key] = stripslashes($_POST[$key]);

	$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}

// Assign the input values to variables for easy reference
$name = $_POST[&quot;name&quot;];
$email = $_POST[&quot;email&quot;];
$message = $_POST[&quot;message&quot;];

// Test input values for errors
$errors = array();
if(strlen($name) &lt; 2) {
	if(!$name) {
		$errors[] = &quot;You must enter a name.&quot;;
	} else {
		$errors[] = &quot;Name must be at least 2 characters.&quot;;
	}
}
if(!$email) {
	$errors[] = &quot;You must enter an email.&quot;;
} else if(!validEmail($email)) {
	$errors[] = &quot;You must enter a valid email.&quot;;
}
if(strlen($message) &lt; 10) {
	if(!$message) {
		$errors[] = &quot;You must enter a message.&quot;;
	} else {
		$errors[] = &quot;Message must be at least 10 characters.&quot;;
	}
}

if($errors) {
	// Output errors and die with a failure message
	$errortext = &quot;&quot;;
	foreach($errors as $error) {
		$errortext .= &quot;&lt;li&gt;&quot;.$error.&quot;&lt;/li&gt;&quot;;
	}
	die(&quot;&lt;span class=&#039;failure&#039;&gt;The following errors occured:&lt;ul&gt;&quot;. $errortext .&quot;&lt;/ul&gt;&lt;/span&gt;&quot;);
}

// Send the email
$to = &quot;YOUR_EMAIL&quot;;
$subject = &quot;Contact Form: $name&quot;;
$message = &quot;$message&quot;;
$headers = &quot;From: $email&quot;;

mail($to, $subject, $message, $headers);

// Die with a success message
die(&quot;&lt;span class=&#039;success&#039;&gt;Success! Your message has been sent.&lt;/span&gt;&quot;);

// A function that checks to see if
// an email is valid
function validEmail($email)
{
   $isValid = true;
   $atIndex = strrpos($email, &quot;@&quot;);
   if (is_bool($atIndex) &amp;&amp; !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen &lt; 1 || $localLen &gt; 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen &lt; 1 || $domainLen &gt; 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == &#039;.&#039; || $local[$localLen-1] == &#039;.&#039;)
      {
         // local part starts or ends with &#039;.&#039;
         $isValid = false;
      }
      else if (preg_match(&#039;/\\.\\./&#039;, $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match(&#039;/^[A-Za-z0-9\\-\\.]+$/&#039;, $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match(&#039;/\\.\\./&#039;, $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if(!preg_match(&#039;/^(\\\\.|[A-Za-z0-9!#%&amp;`_=\\/$\&#039;*+?^{}|~.-])+$/&#039;,
                 str_replace(&quot;\\\\&quot;,&quot;&quot;,$local)))
      {
         // character not valid in local part unless
         // local part is quoted
         if (!preg_match(&#039;/^&quot;(\\\\&quot;|[^&quot;])+&quot;$/&#039;,
             str_replace(&quot;\\\\&quot;,&quot;&quot;,$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid &amp;&amp; !(checkdnsrr($domain,&quot;MX&quot;) || checkdnsrr($domain,&quot;A&quot;)))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}

?&gt;</pre>
<p>That&#8217;s definitely the biggest file we&#8217;ve had yet. Let&#8217;s take a look at what&#8217;s going on.</p>
<pre class="brush: php; gutter: true; first-line: 1">&lt;?php

// Clean up the input values
foreach($_POST as $key =&gt; $value) {
	if(ini_get(&#039;magic_quotes_gpc&#039;))
		$_POST[$key] = stripslashes($_POST[$key]);

	$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}</pre>
<p>This foreach statement is reading all of the variables in the $_POST array and sanitizing them. When you sanitize data, you make sure that it doesn&#8217;t contain anything harmful that could potentially hurt your website.</p>
<pre class="brush: php; gutter: true; first-line: 11">// Assign the input values to variables for easy reference
$name = $_POST[&quot;name&quot;];
$email = $_POST[&quot;email&quot;];
$message = $_POST[&quot;message&quot;];</pre>
<p>As the comment states, all we are doing here is putting each $_POST option into its own variable. That way it will be easier to access the variables later on (less typing).</p>
<pre class="brush: php; gutter: true; first-line: 16">// Test input values for errors
$errors = array();
if(strlen($name) &lt; 2) {
	if(!$name) {
		$errors[] = &quot;You must enter a name.&quot;;
	} else {
		$errors[] = &quot;Name must be at least 2 characters.&quot;;
	}
}
if(!$email) {
	$errors[] = &quot;You must enter an email.&quot;;
} else if(!validEmail($email)) {
	$errors[] = &quot;You must enter a valid email.&quot;;
}
if(strlen($message) &lt; 10) {
	if(!$message) {
		$errors[] = &quot;You must enter a message.&quot;;
	} else {
		$errors[] = &quot;Message must be at least 10 characters.&quot;;
	}
}</pre>
<p>Here we have the actual error testing for each of the variables we just initiated. As you can see, we are basically just performing all of the tests that we did in the Javascript. Every time we encounter an error, we pass the appropriate error message to the $errors array so that we can output all of the errors to the user.</p>
<pre class="brush: php; gutter: true; first-line: 38">if($errors) {
	// Output errors and die with a failure message
	$errortext = &quot;&quot;;
	foreach($errors as $error) {
		$errortext .= &quot;&lt;li&gt;&quot;.$error.&quot;&lt;/li&gt;&quot;;
	}
	die(&quot;&lt;span class=&#039;failure&#039;&gt;The following errors occured:&lt;ul&gt;&quot;. $errortext .&quot;&lt;/ul&gt;&lt;/span&gt;&quot;);
}</pre>
<p>If there were any errors, we output them to the screen in a nicely formatted list, and then we kill the page using the handy die() function.</p>
<pre class="brush: php; gutter: true; first-line: 47">// Send the email
$to = &quot;YOUR_EMAIL&quot;;
$subject = &quot;Contact Form: $name&quot;;
$message = &quot;$message&quot;;
$headers = &quot;From: $email&quot;;

mail($to, $subject, $message, $headers);

// Die with a success message
die(&quot;&lt;span class=&quot;success&quot;&gt;Success! Your message has been sent.&lt;/span&gt;&quot;);</pre>
<p>Now we get to actually send the email! Whoop! First we set all the appropriate variables (change &#8220;YOUR_EMAIL&#8221; to whatever email address you want the messages to be sent to), and then we use PHP&#8217;s built-in mail() function to send the email.</p>
<p>That last line (the die function) is very important. It tells the scrip to kill itself once the email is sent, which does one of two things. If the user has javascript enabled, this die function will send the success message contained in itself back to the javascript file we created in the last step, which will in turn update the #response div with the success text. However, if the user doesn&#8217;t have javascript enabled, the script will simply die and output the success message. It&#8217;s kind of like killing two birds with one stone, isn&#8217;t it?</p>
<pre class="brush: php; gutter: true; first-line: 58">// A function that checks to see if
// an email is valid
function validEmail($email)
{
   $isValid = true;
   $atIndex = strrpos($email, &quot;@&quot;);
   if (is_bool($atIndex) &amp;&amp; !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen &lt; 1 || $localLen &gt; 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen &lt; 1 || $domainLen &gt; 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == &#039;.&#039; || $local[$localLen-1] == &#039;.&#039;)
      {
         // local part starts or ends with &#039;.&#039;
         $isValid = false;
      }
      else if (preg_match(&#039;/\\.\\./&#039;, $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match(&#039;/^[A-Za-z0-9\\-\\.]+$/&#039;, $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match(&#039;/\\.\\./&#039;, $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if(!preg_match(&#039;/^(\\\\.|[A-Za-z0-9!#%&amp;`_=\\/$\&#039;*+?^{}|~.-])+$/&#039;,
                 str_replace(&quot;\\\\&quot;,&quot;&quot;,$local)))
      {
         // character not valid in local part unless
         // local part is quoted
         if (!preg_match(&#039;/^&quot;(\\\\&quot;|[^&quot;])+&quot;$/&#039;,
             str_replace(&quot;\\\\&quot;,&quot;&quot;,$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid &amp;&amp; !(checkdnsrr($domain,&quot;MX&quot;) || checkdnsrr($domain,&quot;A&quot;)))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}

?&gt;</pre>
<p>This is a function that I found online (in <a href="http://www.linuxjournal.com/article/9585?page=0,3">this article</a>) that validates email addresses. It is very handy, and I use it in a lot of my projects because it covers so many different possibilities. If you want to, you can look through and see what it&#8217;s doing, but if you&#8217;re like me and don&#8217;t really care, you can just treat it like a black box and feed it email addresses. It works, believe me.</p>
<h1>Conclusion</h1>
<p>And that&#8217;s it! Now you know how to code a simple and secure contact form that you can easily implement on your own websites. It looks great, is very functional, and has good error checking &#8211; what more could you want?</p>
<h2><a href="http://img.tutwow.com/simplesecurecontact/contact.html">See the final result in action.</a></h2>
<h2><a href="http://www.tutwow.com/wp-content/uploads/2012/01/SimpleSecureContactForm-TutWow.zip">Download the files for this tutorial.</a></h2>
]]></content:encoded>
			<wfw:commentRss>http://www.tutwow.com/htmlcss/create-a-simple-and-secure-contact-form-with-jquery-and-php/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>CSS Remove Textarea Scrollbar</title>
		<link>http://www.tutwow.com/htmlcss/css-remove-textarea-scrollbar/</link>
		<comments>http://www.tutwow.com/htmlcss/css-remove-textarea-scrollbar/#comments</comments>
		<pubDate>Thu, 23 Jun 2011 18:33:58 +0000</pubDate>
		<dc:creator>Ben Lind</dc:creator>
				<category><![CDATA[HTML/CSS]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://www.tutwow.com/?p=1359</guid>
		<description><![CDATA[One of the frustrations of browser testing is that Internet Explorer often renders elements of the page in ways you would never expect. This article will show you how to remove the nasty "disabled" scrollbar from textareas with CSS.]]></description>
			<content:encoded><![CDATA[<p>One of the frustrations of browser testing is that Internet Explorer often renders elements of the page in ways you would never expect. One such example is in scrollbars on textareas. IE (and some other browsers) likes to throw scrollbars into your textareas even when they&#8217;re not necessary.</p>
<p>Thankfully, there is a very simple and easy way to fix this.</p>
<h1>The Solution</h1>
<p>To fix this little annoyance, just add this one line of code to your textarea&#8217;s CSS:</p>
<pre>textarea {
     overflow: auto;
}</pre>
<p>That&#8217;s it! Easy, right? Now the scrollbar will only show when it&#8217;s <em>necessary</em>. In other words, it will be invisible until enough text is written in the textarea to grow beyond its bounds, in which case the bar will be shown.</p>
<h1>Want to <em>really</em> kill that scrollbar?</h1>
<p>Just add this line of code to your textarea&#8217;s CSS, and the scrollbar will <em>never</em> be shown, even if the user fills up the textarea!</p>
<pre>textarea {
     overflow: hidden;
}</pre>
<p>I wouldn&#8217;t recommend doing that unless you have a good reason, though, because you won&#8217;t be able to see what you&#8217;re typing into a textarea with that CSS. It can be useful sometimes, though. Try it out!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tutwow.com/htmlcss/css-remove-textarea-scrollbar/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Set a Page on Fire with Photoshop and CSS</title>
		<link>http://www.tutwow.com/htmlcss/set-a-page-on-fire-with-photoshop-and-css/</link>
		<comments>http://www.tutwow.com/htmlcss/set-a-page-on-fire-with-photoshop-and-css/#comments</comments>
		<pubDate>Fri, 17 Jul 2009 19:28:20 +0000</pubDate>
		<dc:creator>Ben Lind</dc:creator>
				<category><![CDATA[HTML/CSS]]></category>
		<category><![CDATA[Photoshop]]></category>

		<guid isPermaLink="false">http://www.tutwow.com/?p=1016</guid>
		<description><![CDATA[This tutorial will teach you how to set a web page on fire with Photoshop and CSS. The fire hovers over the bottom of the page, and when you scroll down, it stays there. A very cool, but very easy effect!]]></description>
			<content:encoded><![CDATA[<h1>Final Result</h1>
<p>This tutorial will teach you how to set a web page on fire with Photoshop and CSS.  Here&#8217;s a preview of what it will look like:</p>
<p><img class="alignnone" title="Final Result" src="http://img.tutwow.com/FirePage/Preview.jpg" alt="" width="540" height="315" /></p>
<p>If you want to see it in action, you can go to <a title="Fire Page" href="http://img.tutwow.com/FirePage/index.html">this page</a>.</p>
<h1>Step 1</h1>
<p>For the purpose of this tutorial, we will be creating some very basic fire to demonstrate the effect.  If you play around on your own, I&#8217;m sure you can come up with some much better looking fire.</p>
<p>To start off, open up Photoshop and create a new document 500px wide and 300px tall.  Reset your foreground/background colors by pressing D, and go to Filter &gt; Render &gt; Clouds.  You should now have some nice black and white clouds like below:</p>
<p><img class="alignnone" title="Clouds" src="http://img.tutwow.com/FirePage/Step1Clouds.jpg" alt="" width="500" height="300" /></p>
<h1>Step 2</h1>
<p>To colorize the clouds to look more like fire, press Ctrl + U (Image &gt; Adjustments &gt; Hue/Saturation) to bring up the Hue/Saturation dialog.  Inside this dialog, enter these settings:</p>
<p><img class="alignnone" title="Hue/Saturation" src="http://img.tutwow.com/FirePage/Step2Hue.jpg" alt="" width="461" height="367" /></p>
<p>This will give the fire a nice orange glow:</p>
<p><img class="alignnone" title="Orange Clouds" src="http://img.tutwow.com/FirePage/Step2Result.jpg" alt="" width="500" height="300" /></p>
<h1>Step 3</h1>
<p>What we want to do now is make this fire texture into a pattern that we can tile across the web page in a later step.  To do this, go to Filter &gt; Other &gt; Offset, and enter these settings:</p>
<p><img class="alignnone" title="Offset" src="http://img.tutwow.com/FirePage/Step3Offset.jpg" alt="" width="344" height="232" /></p>
<p>This will &#8220;offset&#8221; our texture so that we can see the seam that makes it look horrible when we try to tile it.  We need to remove this seam so that the texture will run together smoothly later.</p>
<p><img class="alignnone" title="Offset Result" src="http://img.tutwow.com/FirePage/Step3OffsetResult.jpg" alt="" width="500" height="300" /></p>
<p>Take the <em>Healing Tool</em> (J), alt + click on some part of the texture other than the seam, and click and drag over the seam to &#8220;heal&#8221; it.  If this doesn&#8217;t work completely, you may need to use the <em>Blur Tool</em> (R) and blur out the rest of the seam.</p>
<p>Your texture should now look something like this:</p>
<p><img class="alignnone" title="Healed" src="http://img.tutwow.com/FirePage/Step3Healed.jpg" alt="" width="500" height="300" /></p>
<h1>Step 4</h1>
<p>The last thing we need to do with this texture is fade it out towards the top.  Double-click on the Background layer (it should be the only layer), and press ok in the dialog that pops up to unlock the layer.</p>
<p>Press Q to enter Quick Mask Mode, take the <em>Gradient Tool</em> (G), and draw out a linear gradient starting from the bottom of the image and stretching up to almost the top.  Press Q again to exit Quick Mask Mode, and then press the Delete key to clear the selection.  This will make the texture fade out like below:</p>
<p><img class="alignnone" title="Fade Out Texture" src="http://img.tutwow.com/FirePage/Step4Result.jpg" alt="" width="500" height="300" /></p>
<p>Our fire texture is now complete.  Press Ctrl + S to save the image to your hard drive.  While you&#8217;re at it, you should create a new folder someplace where you can keep all of the files you use for this tutorial.  Save the image as a PNG file, and name it &#8220;fire.png&#8221;.</p>
<h1>Step 5</h1>
<p>Open up your favorite text editor (I use Coda while I&#8217;m on a Mac, but any old text editor like TextEdit or Notepad will do) and type in some basic HTML:</p>
<pre>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;

&lt;html xml:lang="en-us" xmlns="http://www.w3.org/1999/xhtml"&gt;
 &lt;head&gt;
 &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;
 &lt;title&gt;Fire Page&lt;/title&gt;
 &lt;link href="style.css" media="screen" rel="stylesheet" type="text/css" /&gt;
 &lt;/head&gt;
 &lt;body&gt;
 &lt;/body&gt;
&lt;/html&gt;</pre>
<p>All this is doing is setting up the page with all of the necessary tags that every HTML page has.  The title of the page is &#8220;Fire Page&#8221;, and we are including an external CSS file, &#8220;style.css&#8221;, which we will create later, in it.</p>
<h1>Step 6</h1>
<p>Inside the body of the page, insert this line of code:</p>
<pre>&lt;div id="fire"&gt;&lt;/div&gt;</pre>
<p>This one line is all we need to set up the fire effect.  The real work is done in the CSS file that we will create.</p>
<p>To make the example interesting, put in a bunch of Lorem Ipsum text after the &lt;div id=&#8221;fire&#8221;&gt;&lt;/div&gt; line.  I just went to <a title="Lorem Ipsum Text Generator" href="http://www.lipsum.com/" target="_blank">http://www.lipsum.com/</a>, a Lorem Ipsum text generator, and created 15 paragraphs of dummy lipsum.  Then I copied the paragraphs into my HTML file and wrapped each one in &lt;p&gt; tags.</p>
<p>Save the HTML file we&#8217;ve been working on as &#8220;index.html&#8221;, and put it into the same folder as the image (fire.png) we created before.</p>
<p>You should now have a bland page with a bunch of text in it.  Not much, but the fun is just beginning&#8230;</p>
<h1>Step 7</h1>
<p>Now create a new text file.  This will be the CSS file that styles index.html.  Inside this new file, put in this text:</p>
<pre>body {
 background: #000;
 color: #FFF;
}</pre>
<p>This styles the page so that the background color is black and the font color is white.  This will make our fire texture really stand out from the rest of the page.  After the above code, enter this text:</p>
<pre>#fire {
 background: transparent url(fire.png) repeat-x;
 position: fixed;
 left: 0;
 bottom: 0;
 height: 300px;
 width: 100%;
 z-index: 999;
}</pre>
<p>First, this sets the background of the #fire div to the fire.png file we created before.  Then, it sets the position, height, and width of the div so that it covers the entire bottom of the page.  The last line makes sure that the fire div is always on top of all other content on the page.</p>
<p>Save this file as style.css, and make sure it&#8217;s in the same directory as the index.html and fire.png files.</p>
<h1>Final Result</h1>
<p>That&#8217;s it! If you open up index.html in a web browser, you will see <a title="Fire Page" href="http://img.tutwow.com/FirePage/index.html">this result</a>.  Notice that if you scroll down on the page, the fire will stay hovering over the bottom of it.  It&#8217;s a very versitile effect that you can use for lots of different effects.</p>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tutwow.com/htmlcss/set-a-page-on-fire-with-photoshop-and-css/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Solving the CSS Padding Problem</title>
		<link>http://www.tutwow.com/htmlcss/solving-the-css-padding-problem/</link>
		<comments>http://www.tutwow.com/htmlcss/solving-the-css-padding-problem/#comments</comments>
		<pubDate>Tue, 11 Nov 2008 03:25:07 +0000</pubDate>
		<dc:creator>Ben Lind</dc:creator>
				<category><![CDATA[HTML/CSS]]></category>

		<guid isPermaLink="false">http://www.tutwow.com/?p=383</guid>
		<description><![CDATA[The "CSS padding problem" is what happens when you try to add padding to a lone container.  Instead of the padding pushing the content in, the content pushed the container out.  I have a simple solution to this problem.]]></description>
			<content:encoded><![CDATA[<p>I remember when I first started using CSS, something really ticked me off.  That was that when I had an HTML file with a div in it, and I wanted to add some padding to that div, not only did the content inside of the div get &#8220;padded&#8221;, but the whole div increased in size.  As you can imagine, this got really annoying, until one day I found the solution to the problem.</p>
<p>Let&#8217;s start with an example of the problem.  If I have the following HTML code:</p>
<pre>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"&gt;
	&lt;head&gt;
		&lt;title&gt;CSS Padding Problem&lt;/title&gt;
		&lt;link rel="stylesheet" href="style.css" media="all" /&gt;
	&lt;/head&gt;
	&lt;body&gt;
		&lt;div id="padded"&gt;I want this content to be padded.&lt;/div&gt;
	&lt;/body&gt;
&lt;/html&gt;</pre>
<p><span id="more-383"></span>And the following CSS:</p>
<pre>body {
	margin: 0;
	padding: 10px;
	background: #EEE;
}
#padded {
	width: 950px;
	margin: auto;
	background: #FFF;
}</pre>
<p>Then I will get <a title="See it in action!" href="http://img.tutwow.com/PaddingProblem/Example1/" target="_blank">this result</a>.  It looks pretty bad, because the div doesn&#8217;t have any padding on it.  This is where we run into the problem.  Here&#8217;s what I mean &#8211; if I edit the style.css file and add a &#8220;padding: 20px&#8221; to the #padded selector, then my CSS file will look like this:</p>
<pre>body {
	margin: 0;
	padding: 10px;
	background: #EEE;
}
#padded {
	width: 950px;
	margin: auto;
	background: #FFF;
	padding: 20px;
}</pre>
<p>And in a web browser, the result of that change would look like <a title="See the &quot;padded&quot; version." href="http://img.tutwow.com/PaddingProblem/Example2/" target="_blank">this file</a>.  Looks pretty good, doesn&#8217;t it?  However, if you switch back and forth between the <a title="See it in action!" href="http://img.tutwow.com/PaddingProblem/Example1/" target="_blank">first example</a> and the <a title="See the &quot;padded&quot; version." href="http://img.tutwow.com/PaddingProblem/Example2/" target="_blank">second example</a>, you&#8217;ll see that the div in the second example is a bit wider (40px exactly) than the first one.</p>
<p>By now you might be thinking &#8220;So what?  What&#8217;s the big deal with a div that&#8217;s a little bit wider than it should be?&#8221;  True, for some templates that you create, it won&#8217;t matter if a div is wider than it should be.  However, for designs that are more precise &#8211; i.e. they have been designed to be pixel-perfect &#8211; a little div width change could cause a lot of trouble.</p>
<p>So how do we fix this problem?  Well, there is a surprisingly simple way to fix this problem, and that is by wrapping the #padded div inside another div.  Here is what I mean &#8211; the new HTML file will look like this:</p>
<pre>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"&gt;
	&lt;head&gt;
		&lt;title&gt;CSS Padding Problem&lt;/title&gt;
		&lt;link rel="stylesheet" href="style.css" media="all" /&gt;
	&lt;/head&gt;
	&lt;body&gt;
		&lt;div id="container"&gt;
			&lt;div id="padded"&gt;I want this content to be padded.&lt;/div&gt;
		&lt;/div&gt;
	&lt;/body&gt;
&lt;/html&gt;</pre>
<p>And the new CSS file:</p>
<pre>body {
	margin: 0;
	padding: 10px;
	background: #EEE;
}
#container {
	width: 950px;
	margin: auto;
	background: #FFF;
}
#padded {
	padding: 20px;
}</pre>
<p>As you can see, what I did is just wrap the #padded div inside another div called #container, and then moved all of the styles for the #padded div &#8211; except for the &#8220;padding: 20px&#8221; &#8211; to the styles for the #container div.</p>
<p>Take a look at <a title="See the finished example" href="http://img.tutwow.com/PaddingProblem/Example3/" target="_blank">the finished, &#8220;fixed&#8221;, padding example</a>.  A very easy solution to a maybe not-so-easy problem.</p>
<p>As an Update, I found one <a href="http://www.webhostingsearch.com/articles/20-css-short-hands.php">shortcut list of CSS tricks</a> from my <a href="http://www.webhostingsearch.com">web hosting</a> friend.  This is simple but a good refresher.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tutwow.com/htmlcss/solving-the-css-padding-problem/feed/</wfw:commentRss>
		<slash:comments>50</slash:comments>
		</item>
		<item>
		<title>Quick Tip: CSS 100% Height</title>
		<link>http://www.tutwow.com/htmlcss/quick-tip-css-100-height/</link>
		<comments>http://www.tutwow.com/htmlcss/quick-tip-css-100-height/#comments</comments>
		<pubDate>Thu, 11 Sep 2008 17:53:39 +0000</pubDate>
		<dc:creator>Ben Lind</dc:creator>
				<category><![CDATA[HTML/CSS]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://www.tutwow.com/?p=186</guid>
		<description><![CDATA[A common problem among designers is how to get a div to stretch 100% of the window's height.  There are a few different techniques out there, but I came up with one that is my personal favorite, which I will share with you today.]]></description>
			<content:encoded><![CDATA[<p>I don&#8217;t know about you, but I always get frustrated trying to figure out how to get my layout to stretch vertically to 100% of the page.  I have a div that I want to stretch, but it just doesn&#8217;t stretch.  Now why wouldn&#8217;t it do that?  Today I will share the solution with you.</p>
<p>Say you have coded an HTML file like this:</p>
<pre>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;

&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /&gt;

&lt;title&gt;CSS 100% Height&lt;/title&gt;
&lt;link rel="stylesheet" type="text/css" href="style.css" /&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;div id="content"&gt;
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Vestibulum mollis mauris enim. Morbi euismod magna ac lorem rutrum elementum. Donec viverra auctor lobortis. Pellentesque eu est a nulla placerat dignissim. Morbi a enim in magna semper bibendum.&lt;br /&gt;&lt;br /&gt;
Etiam scelerisque, nunc ac egestas consequat, odio nibh euismod nulla, eget auctor orci nibh vel nisi. Aliquam erat volutpat. Mauris vel neque sit amet nunc gravida congue sed sit amet purus. Quisque lacus quam, egestas ac tincidunt a, lacinia vel velit. Aenean facilisis nulla vitae urna tincidunt congue sed ut dui. Morbi malesuada nulla nec purus convallis consequat. Vivamus id mollis quam. Morbi ac commodo nulla. In condimentum orci id nisl volutpat bibendum. Quisque commodo hendrerit lorem quis egestas. Maecenas quis tortor arcu. Vivamus rutrum nunc non neque consectetur quis placerat neque lobortis. Nam vestibulum, arcu sodales feugiat consectetur, nisl orci bibendum elit, eu euismod magna sapien ut nibh. Donec semper quam scelerisque tortor dictum gravida. In hac habitasse platea dictumst. Nam pulvinar, odio sed rhoncus suscipit, sem diam ultrices mauris, eu consequat purus metus eu velit. Proin metus odio, aliquam eget molestie nec, gravida ut sapien.&lt;br /&gt;&lt;br /&gt;
Phasellus quis est sed turpis sollicitudin venenatis sed eu odio. Praesent eget neque eu eros interdum malesuada non vel leo. Sed fringilla porta ligula egestas tincidunt. Nullam risus magna, ornare vitae varius eget, scelerisque a libero. Morbi eu porttitor ipsum. Nullam lorem nisi, posuere quis volutpat eget, luctus nec massa. Quisque eget odio ac lectus vestibulum faucibus eget in metus. In pellentesque faucibus vestibulum. Nulla at nulla justo, eget luctus tortor. Nulla facilisi. Duis aliquet egestas purus in blandit. Curabitur vulputate, ligula lacinia scelerisque tempor, lacus lacus ornare ante, ac egestas est urna sit amet arcu. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed molestie augue sit amet leo consequat posuere. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Proin vel ante a orci tempus eleifend ut et magna. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus luctus urna sed urna ultricies ac tempor dui sagittis. In condimentum facilisis porta. Sed nec diam eu diam mattis viverra. Nulla fringilla, orci ac euismod semper, magna diam porttitor mauris, quis sollicitudin sapien justo in libero. Vestibulum mollis mauris enim. Morbi euismod magna ac lorem rutrum elementum. Donec viverra auctor lobortis. Pellentesque eu est a nulla placerat dignissim. Morbi a enim in magna semper bibendum. Etiam scelerisque, nunc ac egestas consequat, odio nibh euismod nulla, eget auctor orci nibh vel nisi. Aliquam erat volutpat. Mauris vel neque sit amet nunc gravida congue sed sit amet purus.&lt;br /&gt;&lt;br /&gt;
Quisque lacus quam, egestas ac tincidunt a, lacinia vel velit. Aenean facilisis nulla vitae urna tincidunt congue sed ut dui. Morbi malesuada nulla nec purus convallis consequat. Vivamus id mollis quam. Morbi ac commodo nulla. In condimentum orci id nisl volutpat bibendum. Quisque commodo hendrerit lorem quis egestas. Maecenas quis tortor arcu. Vivamus rutrum nunc non neque consectetur quis placerat neque lobortis. Nam vestibulum, arcu sodales feugiat consectetur, nisl orci bibendum elit, eu euismod magna sapien ut nibh. Donec semper quam scelerisque tortor dictum gravida. In hac habitasse platea dictumst. Nam pulvinar, odio sed rhoncus suscipit, sem diam ultrices mauris, eu consequat purus metus eu velit. Proin metus odio, aliquam eget molestie nec, gravida ut sapien. Phasellus quis est sed turpis sollicitudin venenatis sed eu odio. Praesent eget neque eu eros interdum malesuada non vel leo. Sed fringilla porta ligula egestas tincidunt. Nullam risus magna, ornare vitae varius eget, scelerisque a libero. Morbi eu porttitor ipsum. Nullam lorem nisi, posuere quis volutpat eget, luctus nec massa. Pellentesque aliquam lacinia tellus sit amet bibendum. Ut posuere justo in enim pretium scelerisque. Etiam ornare vehicula euismod. Vestibulum at risus augue. Sed non semper dolor. Sed fringilla consequat velit a porta. Pellentesque sed lectus pharetra ipsum ultricies commodo non sit amet velit. Suspendisse volutpat lobortis ipsum, in scelerisque nisi iaculis a. Duis pulvinar lacinia commodo. Integer in lorem id nibh luctus aliquam. Sed elementum, est ac sagittis porttitor, neque metus ultricies ante, in accumsan massa nisl non.
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<p><span id="more-186"></span></p>
<p><span>And you have a CSS file like this:</span></p>
<pre>body {
	margin: 0;
	padding: 0;
}
#content {
	background: #EEE;
	border-left: 1px solid #000;
	border-right: 1px solid #000;
	padding: 0 20px 0 20px;
	margin: auto;
	font: 1.5em arial, verdana, sans-serif;
	width: 960px;
	height: 100%;
}</pre>
<p>That gives you <a title="Example 1" href="http://img.tutwow.com/VerticalStretch/Example1/VerticalStretch.html" target="_blank">this example file</a>.  As you can see, the content box on that page doesn&#8217;t stretch to the whole height of the page, even though we added the &#8220;height: 100%;&#8221; line to the CSS file.  Why is that?</p>
<p>Let me give you a different way of thinking about HTML.  HTML is pretty much just a bunch of containers stacked inside each other.  So in our page, first we have the &lt;html&gt; container, then the &lt;body&gt; container inside of that, and finally the &lt;div id=&#8221;content&#8221;&gt; container inside of <em>that</em>.  When we put content into one of those boxes, it stretches that box and all the boxes containing that box so that they can hold the new content.  So when we put our text into the &lt;div id=&#8221;content&#8221;&gt; box, that box streches, which in turn stretches all of the boxes that it is in (in our case the &lt;body&gt; and &lt;html&gt; boxes).</p>
<p>When we put the &#8220;height: 100%;&#8221; style onto the &lt;div id=&#8221;content&#8221;&gt; box, what we are doing is telling it to stretch to the full height <em>of the box that it is in</em>.  In this example, the box that it is in is the &lt;body&gt; box.  So the &lt;div id=&#8221;content&#8221;&gt; box is 100% of the height of the &lt;body&gt; box.  Well, how tall is the &lt;body&gt; box?  It&#8217;s just as tall as the &lt;div id=&#8221;content&#8221;&gt; box, because we never told it how tall it should be!  So when we put the &#8220;height: 100%;&#8221; style onto the &lt;div id=&#8221;content&#8221;&gt; box, we are just telling it to be as tall as itself!</p>
<p>To fix this, we need to tell the &lt;body&gt; box to get bigger.  But then we run into the same problem with the &lt;html&gt; box &#8211; it is only as big as the &lt;body&gt; box!  So to fix our problem (to get the &lt;div id=&#8221;content&#8221;&gt; box to stretch the whole height of the page), we need to tell the &lt;html&gt; and &lt;body&gt; boxes to be the full height of the page.</p>
<p>So if we change our CSS file to this:</p>
<pre>html {
	height: 100%;
}
body {
	margin: 0;
	padding: 0;
	height: 100%;
}
#content {
	background: #EEE;
	border-left: 1px solid #000;
	border-right: 1px solid #000;
	padding: 0 20px 0 20px;
	margin: auto;
	font: 1.5em arial, verdana, sans-serif;
	width: 960px;
	min-height: 100%;
}</pre>
<p>And that&#8217;s it!  <a title="Example 2" href="http://img.tutwow.com/VerticalStretch/Example2/VerticalStretch.html" target="_blank">This is what we have now</a>.  The content box is now stretched to the full height of the page!</p>
<p><strong>Update:</strong> Thanks to some very helpful comments, I have updated the final CSS so that the #content div now has &#8220;min-height: 100%&#8221; instead of just &#8220;height: 100%&#8221;. This is so that if the content of the #content div extends beyond the height of the window, the background will expand as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tutwow.com/htmlcss/quick-tip-css-100-height/feed/</wfw:commentRss>
		<slash:comments>224</slash:comments>
		</item>
		<item>
		<title>My Coding Style</title>
		<link>http://www.tutwow.com/htmlcss/my-coding-style/</link>
		<comments>http://www.tutwow.com/htmlcss/my-coding-style/#comments</comments>
		<pubDate>Wed, 18 Jun 2008 15:34:21 +0000</pubDate>
		<dc:creator>Ben Lind</dc:creator>
				<category><![CDATA[HTML/CSS]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://www.tutwow.com/WP25/?p=10</guid>
		<description><![CDATA[A lot of people just throw a bunch of code into a file and hope it runs.  If it doesn't run, it's quite a nightmare to edit it again since it isn't formatted well.  However, I like to format my code in a very strict way, which I'll share with you today.]]></description>
			<content:encoded><![CDATA[<p>Over the past few years, I have learned many different programming languages.  Having typed program after program (&#8220;Hello World&#8221; after &#8220;Hello World&#8221;), I have come up with a very specific programming style for formatting my code.   Instead of just throwing a bunch of code into a text editor &#8211; hoping that I can decipher it when I look at it again in a few months &#8211; I carefully indent all of my code to the correct width, and use a lot of comments.  Below, I have put together some of my most-used practices so that you can (hopefully) benefit from and build off of them.</p>
<h2>1. Indenting Two Spaces</h2>
<p>One of the most obvious ways to make your code more readable is to indent all of your lines to the correct width.  I usually use two spaces for my tabs, an option you can specify in most text editors.</p>
<p><a href="http://www.tutwow.com/WP25/wp-content/uploads/2008/06/indent2spaces.jpg" rel="lightbox[10]"><img class="alignnone size-full wp-image-11" title="Indenting 2 Spaces" src="http://www.tutwow.com/WP25/wp-content/uploads/2008/06/indent2spaces.jpg" alt="Indenting 2 Spaces" width="500" height="219" /><span id="more-10"></span></a></p>
<h2>2. Code Bracket Placement</h2>
<p>As I said before, it&#8217;s always nice to keep your code style the same throughout all of your code.  One of the things I am a little &#8220;finicky&#8221; about is the placement of the code brackets that surround my code blocks (if statements, while loops, etc.).</p>
<p>I place my beginning bracket one space after the ending parenthesis of the code block header.  Take a look at this image to see what I mean:</p>
<p><a href="http://www.tutwow.com/WP25/wp-content/uploads/2008/06/1spacebeforebracket.jpg" rel="lightbox[10]"><img class="alignnone size-full wp-image-12" title="Placement of Beginning Bracket" src="http://www.tutwow.com/WP25/wp-content/uploads/2008/06/1spacebeforebracket.jpg" alt="Placement of Beginning Bracket" width="500" height="219" /></a></p>
<h2>3. Comment, Comment, Comment</h2>
<p>Alright, I admit it, I&#8217;m a comment freak.  I go <em>wild</em> with comments all over the place, and I have descriptions of almost every line of code in my files.  I find that if I stick to one format for all of my comments, it makes the overall readability a whole lot better.</p>
<p>When I comment whole sections of code, using the comment as a sort of &#8220;header&#8221;, I put my header text inside a multi-line comment, and place this right before the beginning of the section of code that I&#8217;m describing.</p>
<p><a href="http://www.tutwow.com/WP25/wp-content/uploads/2008/06/headercomments.jpg" rel="lightbox[10]"><img class="alignnone size-full wp-image-13" title="Header Comments" src="http://www.tutwow.com/WP25/wp-content/uploads/2008/06/headercomments.jpg" alt="Header Comments" width="500" height="219" /></a></p>
<p>When describing just a single line, I use a single-line comment, and tab it one or two tabs from the line I&#8217;m describing &#8211; like this:</p>
<p><a href="http://www.tutwow.com/WP25/wp-content/uploads/2008/06/singlelinecomments.jpg" rel="lightbox[10]"><img class="alignnone size-full wp-image-14" title="Single Line Comments" src="http://www.tutwow.com/WP25/wp-content/uploads/2008/06/singlelinecomments.jpg" alt="Single Line Comments" width="500" height="219" /></a></p>
<h2>4. Parenthesis and Brace Padding<strong><br />
</strong></h2>
<p>To make my code more readable, I add spaces inside all of my parentheses and square braces as a kind of &#8220;padding&#8221; for them.  This can look strange at first, but if you get used to it, you&#8217;ll see how much more readable it can make things.</p>
<p><a href="http://www.tutwow.com/WP25/wp-content/uploads/2008/06/parenthesispadding.jpg" rel="lightbox[10]"><img class="alignnone size-full wp-image-15" title="Parenthesis Padding" src="http://www.tutwow.com/WP25/wp-content/uploads/2008/06/parenthesispadding.jpg" alt="Parenthesis Padding" width="500" height="219" /></a></p>
<h2>Conclusion</h2>
<p>I hope that everyone who reads this post gets something out of it, and applies it to their own coding.  Now don&#8217;t misunderstand me &#8211; this is <em>not</em> the only way to format your code &#8211; there are <em>so</em> many different ways you can do this, and the important thing is that you find the style that you&#8217;re comfortable with and stick with it.</p>
<p>Until next time, happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tutwow.com/htmlcss/my-coding-style/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>HTML Code Export</title>
		<link>http://www.tutwow.com/htmlcss/html-code-export/</link>
		<comments>http://www.tutwow.com/htmlcss/html-code-export/#comments</comments>
		<pubDate>Sun, 25 May 2008 01:33:19 +0000</pubDate>
		<dc:creator>Ben Lind</dc:creator>
				<category><![CDATA[HTML/CSS]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://www.tutwow.com/WP25/?p=6</guid>
		<description><![CDATA[Many people are picky about how their code looks, especially how it is indented.  I am one of these people, and whenever I see badly indented code, I can't stand it.  So I found some software that helped me out and can help you too.]]></description>
			<content:encoded><![CDATA[<p>This is a message to all of you HTML coders out there who have spent hours indenting their code lines so that they look just right, only to get them messed up again.  I know how you feel!  I&#8217;m one of those people who need to have their code indented to just the right length so that I can think straight.</p>
<p>Well, now there&#8217;s a solution.  I&#8217;ve been searching around the web, and I just stumbled onto this program called HTML Code Export.  What it does (or what I use it for) is it takes HTML code that you enter, and it indents everything so that it&#8217;s nice and tidy.  Pretty slick, huh?  I can&#8217;t believe I didn&#8217;t think of this earlier &#8211; it would have saved my hours of headaches!</p>
<p>Make sure to hop over to <a title="HTML Code Export" href="http://www.highdots.com/html-code-export/" target="_blank">the download site</a>, and get your copy of this amazing time saving program now!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tutwow.com/htmlcss/html-code-export/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

