21/4/24, 20:46 CSS Layout - Horizontal & Vertical Align
Try it Yourself »
Tutorials Exercises Services Sign Up Log in
HTML
CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C
Note: Center aligning has no effect if the width property is not set (or set to 100%).
Center Align Text
To just center the text inside an element, use text-align: center;
This text is centered.
Example
.center {
text-align: center;
border: 3px solid green;
}
Try it Yourself »
Tip: For more examples on how to align text, see the CSS Text chapter.
Center an Image
To center an image, set left and right margin to auto and make it into a block
element:
Example
img {
display: block;
margin-left: auto;
https://www.w3schools.com/css/css_align.asp 2/10
21/4/24, 20:46 CSS Layout - Horizontal & Vertical Align
margin-right: auto;
Tutorials
width: 40%; Exercises Services Sign Up Log in
}
HTML
CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C
Try it Yourself »
Left and Right Align - Using position
One method for aligning elements is to use position: absolute; :
In my younger and more vulnerable
years my father gave me some
advice that I've been turning over
in my mind ever since.
Example
.right {
position: absolute;
right: 0px;
width: 300px;
border: 3px solid #73AD21;
padding: 10px;
}
Try it Yourself »
Note: Absolute positioned elements are removed from the normal flow, and can overlap
elements.
Left and Right Align - Using float
Another method for aligning elements is to use the float property:
Example
.right {
float: right;
width: 300px;
border: 3px solid #73AD21;
padding: 10px;
}
https://www.w3schools.com/css/css_align.asp 3/10