To horizontally center a block content, image or other element inside our container what we must do is the following:
div { width: 400px; margin: auto; }
We define the width of the element, because if it occupies 100% or this was not defined, it would have no effect to apply margin: auto. This last style is the one that really does the job, because it tells the browser that the remaining space occupied by the defined element is divided into equal parts and is applied to both sides of the element.
In the case of responsive images, although its width is 100%, the height will be auto, so the image will be proportional to the size of the container in which it is located. In this aspect we can indicate a fixed width to the container and apply in the same way to the image a margin: auto.
contenedor { width: 75%; } contenedor img { display: block; width: 100%; height: auto; margin: auto; }
Resulting in a horizontally centered image.
And that’s all, we hope you find this information useful.