How to Work with Dialog in CSS3

By John Paul Mueller

Both HTML5 and JavaScript make it possible to display dialog boxes in CSS3. For example, you can see a combination of an HTML5/CSS3 dialog box that doesn’t require the use of JavaScript at Code Project.

Adding JavaScript means you have instant access to the alert(), confirm(), and prompt() functions for limited direct dialog box display. You also have all of the functionality that JavaScript can provide to create truly amazing custom dialog boxes.

The problem with all of these approaches is that you may need to write a considerable amount of code to obtain the desired result. On the other hand, using jQuery UI makes it possible to create these dialog box types without much coding at all:

  • Basic

  • Animated

  • Modal

  • Modal with confirmation

  • Modal form

  • Modal message

Additionally, even a basic jQuery UI dialog box provides better functionality than the JavaScript alert() function. You can move the dialog box around, resize it, and close it by using the X in the upper-right corner. The text can also be decorated in various ways because it uses standard HTML input.

The following example begins by creating an internal style to use to decorate the text. (You can find complete code for this example in the Chapter 06Widgets folder of the downloadable code as DialogBox.HTML.)

<style type="text/css">
 font-family: Arial, Helvetica, sans-serif;
 color: SaddleBrown;
 background-color: Bisque;
 color: Maroon;
 font-style: italic;
 font-size: larger;

This code provides a few simple changes to the text — just enough so you can see the custom CSS at work. The following code creates the dialog box on screen automatically when you load the page.

<h1>Creating a Simple Dialog Box</h1>
<div id="DialogContent"
 title="Simple Dialog Example"
 <p class="Normal">
 This is some
 <span class="Emphasize">interesting</span>
 text for the dialog box!
<script type="text/javascript">

The dialog box requires two elements — a container, such as a <div>, to hold the caption in the title attribute and a textual element, such as a <p>, to hold the content. Notice that the paragraph text includes a <span> in this case to provide emphasis to the word interesting. You can format the content in any way desired without modifying the call to jQuery UI at all.

The script uses an id selector to access the <div>. It then makes a simple call to dialog() to display the dialog box on screen. Notice that it provides a pleasing appearance and it contains formatted content, unlike the alert() function, which provides an austere, square dialog box that lacks any formatting.