CSS Align
CSS (Cascading Style Sheets) is a stylesheet language used to describe the presentation of a document written in HTML or XML. CSS layout refers to the arrangement of elements on a web page, and horizontal and vertical alignment are crucial aspects of designing the layout.
Horizontal Alignment
Text Alignment:
text-align: This property is used to horizontally align text within a container. Common values include left, right, center, and justify.
Block Element Alignment
margin: Adjusting the left and right margins can effectively center a block-level element horizontally.
Flexbox
Flexbox is a powerful layout model that allows for the easy alignment of items within a container, both horizontally and vertically.
Vertical Alignment:
Vertical Align Property
vertical-align: This property is often used with inline or table-cell elements to vertically align them within their parent.
line-height:Used for vertically aligning inline or inline-block elements.
Example
.center { line-height: 200px; height: 200px; border: 3px solid green; text-align: center; } /* If the text has multiple lines, add the following: */ .center p { line-height: 1.5; display: inline-block; vertical-align: middle; }You can click on above box to edit the code and run again.
Output
I am vertically and horizontally centered.
align-items (Flexbox):Used for aligning items vertically in a flex container.
align-self (Flexbox):Used for aligning a specific flex item within a container.
Combination (Centering both horizontally and vertically):
flexbox:Combining justify-content and align-items in a flex container centers both horizontally and vertically.
These are just a few examples, and the choice of which to use depends on the specific layout requirements of your project. Flexbox and Grid are particularly powerful layout tools in CSS for achieving both horizontal and vertical alignment in a flexible and responsive way.