How to Create a Draggable Interface in CSS3

Sometimes a user needs to reposition screen elements to make them easier to see or work with. In CSS3, creating an environment in which the user can move items around need not involve writing reams of code. In fact, all you really need is a single method called draggable().

The following code shows the method used to create a draggable paragraph in this example. (You can find complete code for this example in the \Chapter 06\Interactions folder of the downloadable code as DragContent.HTML.)

$(function()
 {
 $("#MoveMe").draggable();
 });

This code is interesting because it actually creates a jQuery anonymous function that extends the jQuery environment rather than working with any particular page feature.

The focus of this call is a paragraph (<p> tag) with an id of MoveMe. All you need to do is access that member and call draggable() to make it move around. Try the downloadable example and you find that you can move the paragraph anywhere you want on the page.

To create a movable box, this example relies on a custom style. The style creates a border, allows plenty of room for the text, and then centers the text both horizontally and vertically. Here’s the style used for this example:

#MoveMe
{
 border: solid;
 width: 200px;
 height: 5em;
 text-align: center;
 line-height: 5em;
}

Many developers experience problems vertically centering text within a <p> tag. You can find a number of ways to perform this task. However, one of the easiest ways to get the job done in a platform- and browser-consistent manner is to use the line-height style as shown in the example.

The trick though is to set the height and line-height styles to the same value — the text will always appear in the middle.

blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.