1. Computing

Video:Tips for Centering With CSS

with Dimitri LaBarge

Want to learn how to center text or images with CSS? This video will show you how to use CSS to make your webpage look great.See Transcript

Transcript:Tips for Centering With CSS

Hi, this is Dimitri LaBarge for About.com, and today we're going to talk about centering with CSS, or Cascading Stye Sheets.

What Is the Purpose of CSS?

CSS is a very powerful tool for defining how things should be organized on a web page. There are four main ways to do this - depending on what you’re arranging. Let’s look at each of them.

Paragraph Centering With CSS

Let’s start with defining paragraph classes in CSS. Up in the top where you’re defining styles, type the following:p.centered { text-align: center; } That defines a paragraph class called centered, and sets a centered text alignment. Now, to make a paragraph centered, type the following:p class=”centered”This is centered text! /p

This says that this paragraph is connected to your paragraph class CENTERED that you just defined. Everything in that class will appear as centered text-aligned.

Using DIV Tags to Center

Similarly, you can set an entire section centered using the DIV tag. Create a style like you did earlier, but one that looks like this:div.centered { margin-left: auto; margin-right: auto; width: 8em; }Div creates a master element where you can place different elements. Now you apply that to your display text:div class="centered">This entire block is centered, but the text inside it is left aligned. /divHere the main block itself will be centered. But within it, the text will be defined as standard margin-left text.

Centering Images With CSS

Okay, let’s talk about images. It’s very similar to creating the DIV tag above:img.centered { display: block; margin-left: auto; margin-right: auto; }This sets the image up as a block element that should be centered. Then the image code would look like this:img src="itsme.jpg" alt="Lookatme" class="center" /You would call the class right in the image tag itself.

Centering With CSS 2

CSS 2 makes it a little tricky if you want to vertically center an element, as there isn’t formal support for this, and different browsers display attempts at this differently. This is the currently recommended method for doing this.

Create a DIV element, and then decided on a fixed minimum height. Now, as you create a VCENTER class, define the element as a table cell, and then align it to middle..vcenter { min-height: 12em; display: table-cell; vertical-align: middle; }Then, define your text with the vcenter class, using the DIV tag.div class="vcenter" p This text is vertically centered in the box./p /divIt should look roughly like this.

Thanks for watching. To learn more, visit us on the web at About.com.

About videos are made available on an "as is" basis, subject to the User Agreement.

©2013 About.com. All rights reserved.