Page 94 - CSS
P. 94
MORE INFORMATION
• The element is being positioned according to the first non-static parent (position: relative,
absolute, or fixed). Explore more in this fiddle and this documentation topic.
• For horizontal-only centering, use left: 50% and transform: translateX(-50%). The same goes
for vertical-only centering: center with top: 50% and transform: translateY(-50%).
• Using a non-static width/height elements with this method of centering can cause the
centered element to appear squished. This mostly happens with elements containing text,
and can be fixed by adding: margin-right: -50%; and margin-bottom: -50%;. View this fiddle for
more information.
Using Flexbox
HTML:
<div class="container">
<img src="http://lorempixel.com/400/200" />
</div>
CSS:
html, body, .container {
height: 100%;
}
.container {
display: flex;
justify-content: center; /* horizontal center */
}
img {
align-self: center; /* vertical center */
}
View Result
HTML:
<img src="http://lorempixel.com/400/200" />
CSS:
html, body {
height: 100%;
}
body {
display: flex;
justify-content: center; /* horizontal center */
align-items: center; /* vertical center */
}
https://riptutorial.com/ 72

