Center Align Element
Use margin: auto
.centerElement {
margin: auto;
width: 50%;
border: 3px solid var(--contrastColor1);
}This div element is centered.
Center Align Text
Use text-align: center
.centerElement {
text-align: center;
border: 3px solid var(--contrastColor1);
}The text is centered.
Center Image
Use display: block and margin: auto
.centerImage {
display: block;
margin: auto;
border: 3px solid var(--contrastColor1);
}
Left and Right Align - Using Float
Use float: right
.rightFloat {
float: right;
width: 75%;
border: 3px solid var(--contrastColor1);
}The div element is aligned right, but can overlap because it's removed from the normal flow.
Left and Right Align - Using Position
Use position: absolute and right: 0px
.rightPosition {
position: absolute;
right: 0px;
width: 75%;
border: 3px solid var(--contrastColor1);
}The div element is aligned right, but can overlap because it's removed from the normal flow.
Left and Right Align - Using Flex Box
Use the following on the parent container.
display: flex;justify-content: flex-end;justify-contentproperty also has values:center,flex-start,space-around,space-between, andspace-evenly
.rightFlexBox {
display: flex;
justify-content: flex-end;
}
.rightFlexBox > div {
border: 3px solid var(--contrastColor1);
}
<div class="rightFlexBox">
<div>The div element is aligned right.</div>
</div>The div element is aligned right.
Center Vertically - Using Flex Box
Use the following on the parent container.
display: flex;justify-content: center;align-items: center;
.centerVerticallyFlexBox {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
border: 3px solid var(--contrastColor2);
}
.centerVerticalFlexBox > div {
border: 3px solid var(--contrastColor1);
}
<div class="centerVerticallyFlexBox">
<div>The div element is centered vertically.</div>
</div>The div element is centered vertically.
Reference
Examples from W3 School: www.w3schools.com/css/css_align.asp