Mad Libs-style HTML forms

I recently had the opportunity to create a Mad Libs-style contact form for a client, where the input fields are in-line with a block of text and the label is positioned below. It was actually a lot easier than I anticipated.

To achieve the effect, I placed the input within a label and applied some styles to get the label to display nicely within a paragraph of text.

<p>
	My name is
	<label><input type="text" name="name" size="15" />Your Name</label>
	and I was recently attacked by a
	<label><input type="text" name="animal" size="15" />Animal</label>.
	I was so
	<label><input type="text" name="feeling" size="15" />Feeling</label>
	that I
	<label><input type="text" name="verb" size="15" />Verb</label>
	my
	<label><input type="text" name="noun" size="15" />Noun</label>.
</p>

In order to get the fields to display appropriately, I needed to do some clever positioning of the labels and inputs, as well as having reasonable spacing between lines in the paragraph.

input
{
	display: block;
	padding: 0.25em;
	text-align: center;
}

label
{
	display: inline-block;
	font-size: 0.6em;
	line-height: 1.25em;
	position: relative;
	text-align: center;
	top: 0.75em;
	vertical-align: top;
}

p
{
	line-height: 2.5em;
	margin-left: 10%;
	margin-bottom: 1em;
	text-align: justify;
	width: 80%;
}

This works beautifully, but there was one thing that needed to be addressed. Occasionally, periods that came after an input field would wrap to the next line, and it required some additional markup surrounding the label and period in order to disable the word-wrapping.

<style>
	.nowrap { white-space: nowrap; }
</style>

<p>
	This is the end of the 
	<span class="nowrap">
		<label>
			<input />
			Noun
		</label>
		.
	</span>
</p>

View full source for the Mad Libs® style Love Letter

Leave a Reply

Your email address will not be published. Required fields are marked *