margin: auto;
width: 50%;
border: 3px solid green;
padding: 10px;
}
To center horizontally for a block element (like div) you can use
use margin: auto.
Note: The element after occupying certain space, the space left
will be divided equally for both sides.
To center an image, set margin-left and margin-right to auto and make the image become a block- like element as mentioned above.
img {
display: block;
margin-left: auto;
margin-right: auto;
width: 40%;
}
To center an image, set margin-left and margin-right to auto and do
for the image to become a block element as mentioned above.
In CSS there is a text-align attribute that allows you to align content text to the left, middle, or right of the element by values:
Note : The text-align attribute also applies only to block elements because inline only occupies a sufficient width of its content.
Another method to align elements is to use position: absolute.
.right {
position: absolute;
right: 0px;
width: 300px;
border: 3px solid purple;
padding: 10px;
}
The float attribute is also used to align elements.
.right {
float: right;
width: 300px;
border: 3px solid purple;
padding: 10px;
}
Note : If a floating element is higher than the parent element, it will cause an outflow of content. To fix this, we use clearfix overflow: auto:
.clearfix {
overflow: auto;
}
There are many ways to center a vertical element in CSS. The simplest solution is to use padding.
.center {
padding: 70px 0;
border: 3px solid green;
To align both horizontally and vertically, use padding with the attribute text-align: center.
.center {
padding: 70px 0;
border: 3px solid green;
text-align: center;
}
You also have another way to center vertically by using the line-height attribute with the same value as the height attribute .
.center {
line-height: 200px;
height: 200px;
border: 3px solid green;
text-align: center;
}
.center p {
line-height: 1.5;
display: inline-block;
vertical-align: middle;
}
If you don't use the above padding and line-height , you can use the third way to use position and transform:
.center {
height: 200px;
position: relative;
border: 3px solid purple;
}
.center p {
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}