Code highlights logo

Learn

Visual Rules

Text Align

In this lecture, we'll explore how to align text horizontally and vertically using the text-align property.

Aligning Text Horizontally

The horizontal alignment of text can be set with the text-align property. The text-align property can have four values: left, right, center, and justify.

  • left: This value aligns text to the left edge of the containing block.
  • right: This value aligns text to the right edge of the containing block.
  • center: This value centers text horizontally within its containing block.
  • justify: This value justifies the text. Justified text is aligned to both the left and right edges of its containing block.
1p {
2 text-align: center; /* centers text within its containing block */
3}

Aligning Text Vertically

The vertical alignment of text can be set with the line-height property. The line-height property specifies the height of a line box, which determines the placement of text within that line.

1p {
2 line-height: 1.5; /* sets the height of each line equal to 1.5 times the font size */
3}

We can vertically align text within a block element by setting the height of the containing block to be equal to the line-height of the text, and then setting the line-height property of the text to be equal to the height of the containing block.

1.container {
2 height: 200px; /* sets the height of the containing block */
3 display: flex;
4 align-items: center; /* vertically centers text within the containing block */
5}
6
7.container p {
8 line-height: 200px; /* sets the height of the line box equal to the height of the containing block */
9}

By using these techniques and properties, we can control the horizontal and vertical alignment of text and create visually pleasing designs.


Instructions

1.

Add a rule to style the h2 element to be aligned to the right.

2.

Add a rule to style the p elements to be aligned to the left.

3.

Add a rule to style the .title class to be aligned to the center.

Sign up to start coding

Already have an account?

Sign In

Course content