Text Alignment
Exercise
- In the "index.html" file, replace the code with the following:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS</title> <link rel="stylesheet" href="./css/styles.css"> </head> <body> <h1>Text Alignments</h1> <p id="default-alignment">This will be the default text alignment.</p> <p id="center-alignment">This is a second paragraph with center alignment.</p> <p id="right-alignment">This is a third paragraph with right alignment.</p> </body> </html>
- Save.
- If "Live Server" is not already running, right-click anywhere in the editor and select "Open with Live Server" from the context menu.
- In the "styles.css" file, replace the code with the following:
body { font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif; } h1 { font-family: 'Courier New', Courier, monospace; } #default-alignment { text-align: left; } #center-alignment { text-align: center; } #right-alignment { text-align: right; }
- Save.
- In the browser, you should see the following:
Code Walkthrough and Explanation
text-align
text-align
is a CSS property used to control the horizontal alignment of text within an element.
It can
be used to align text to the left, center, right, or justify it. Here are the most common values used:
left
: Aligns the text to the left edge of the element.center
: Centers the text horizontally within the element.right
: Aligns the text to the right edge of the element.justify
: Expands the spaces between words to fill the entire line, creating a clean edge on both the left and right sides of the text.
The text-align
property can be applied to block-level elements like paragraphs and headings, as
well as
to inline-level elements like span and a tags.
Experiment with the Code
- Try setting the default text-alignment of the page to
justify
by using the universal selector.
Video and Code References
Questions? Subscribe and ask in the video comments: