bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/CSS/CSS Foundations
CSS•CSS Foundations

CSS Horizontal Align

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind CSS Horizontal Align?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___: auto;
3Order

Put the learning moves in the order that makes the concept easiest to apply.

Center Align an Image
Center Align Block Elements
Horizontal Centering

Horizontal Centering

There are several ways to horizontally center elements in CSS, depending on the type of element.

Center Align Block Elements

Use margin: auto; , to horizontally center a block-level element (like <div>).

Also specify a width for the element, to prevent it from stretching out to the edges of its container.

Note

Center aligning has no effect on block-level elements if the width property is not set (or set to 100%).

Below, the <div> element is centered and has a width of 50% (and the remaining space will be split equally between the left and right margins):

This div element is centered.

Example

Formatted code
.center {
  margin: auto;
  width: 50%;
  border: 3px solid green;
  padding: 10px;
}

Live preview

Center Align Text

To center the text inside a block-level element, use text-align: center; .

This text is centered.

Example

Formatted code
p {
  text-align: center;
}

Live preview

Tip

For more examples on how to align text, see the CSS Text chapter.

Center Align an Image

To center an image, set margin-left and margin-right to auto , and also turn the image into a block element:

Example

Formatted code
img {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 40%;
}

Live preview

Left and Right Align - Using position

Another method for aligning elements is to use position: absolute; :

Note

Absolute positioned elements are removed from the normal flow, and can overlap other elements.

This <div> element is positioned to the right, with the position: absolute property.

Example

Formatted code
.right {
  position: absolute;
  right: 0px;
  width: 300px;
  border: 3px solid green;
  padding: 10px;
}

Live preview

Left and Right Align - Using float

Another method for aligning an element to the left or right, is to use the float property:

Example

Formatted code
.right {
  float: right;
  width: 300px;
  border: 3px solid green;
  padding: 10px;
}

Live preview

Previous

CSS Center Align

Next

CSS Vertical Align