If you always struggled with alignment in your html, and corresponding CSS code, especially with horizontal alignment, this may be helpful to you.
The key idea is how to center horizontally any html element on a web page, without setting exact positioning values, in order to provide a responsive design. Knowing that the width of these elements is considered to be smaller than the viewport width.
I discovered these two key elements to easily accomplish this alignment:
If you have block elements, all you have to do is to set their left and right margin properties to auto.
For example, a div can be centered as follow:
div {
width: 35%;
margin: auto;
}
In the code above, I set all the margin values to auto.
If you have inline elements, just change their display property to block, then set the corresponding left and right margins to auto. The example below is an example of how to center an img horizontally:
img {
width:90%;
display: block;
margin: 10px auto;
}
In the code above, I also set; at the same time, the margin-top and margin-bottom to 10px.
For block text elements, like headers and paragraphs consider two situations:
In the first case, all you have to do, is to set the text-align property to center.
p {
text-align:center;
}
For the second case, you have also to set the margin-right and margin-left properties to auto.
p {
text-align: center;
background-color:#98817b;
color:white;
width: 50%;
margin: 10px auto;
}
For the inline text element, you have to first set their display property to block, then consider the previously cited cases:
span{
text-align:center;
display:block;
}
span{
text-align:center;
display:block;
background-color:#6d9a79;
width: 50%;
color: white;
margin: 10px auto;
}
I combined different types of elements, and centered all of them horizontally applying the rules I talked about above, and here is the result:
The corresponding code can be found here. I added to enhance the responsiveness of the display, minimum-width values for most of the elements. The image element being automatically resized according to its parent div element.
See the Pen Center an Image Horizontally by Amina (@aminaAIM) on CodePen.