I've been diligently working on a website, complete with a header and an image within the body. However, I faced a challenge while attempting to center the image within the body section. The image stubbornly remained fixed on the left, refusing to budge.
You can find the code for my project on GitHub.
Initially, I made the following adjustments:
- I added
height: 100vh;to the.gridclass, aiming to make it occupy the full viewport height. - Applied
text-align: center;to the.grid divfor centralized content within each grid item. - Added
max-width: 100%;andmax-height: 100%;to#plattegrondto prevent the image from exceeding container dimensions.
Despite my expectations to horizontally center the image in the middle of the page, the outcome was unexpected. The image got smaller, not by my intention, yet it did center horizontally. However, it stubbornly remained on the left side of the website and failed to center vertically in the middle of the page.
In an attempt to find a solution, I made additional changes:
- I considered changing the display property of the
.gridclass toflexfor easier centering of child elements. - Set
justify-content: center;andalign-items: center;to achieve both horizontal and vertical centering. - Adjusted the width and height properties for
#plattegrondto fill the container while maintaining the original aspect ratio.
Unfortunately, the outcome was not as expected. The image centered, but it became excessively large, causing issues with other pages linked to the same stylesheet. This presented an unexpected challenge in maintaining consistent sizing across the entire website.
For this task, I sought guidance from ChatGPT.
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
justify-content: center;
align-items: center;
background-color: #4883BD;
height: 100vh; /* Set the height to fill the viewport height */
}
.grid div {
text-align: center; /* Center the content within each grid item */
}
#plattegrond {
max-width: 100%; /* Ensure the image does not exceed the container width */
max-height: 100%; /* Ensure the image does not exceed the container height */
}
.grid {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #4883BD;
}
#plattegrond {
width: 100%; /* Set the width to 100% to fill the container */
height: auto; /* Maintain the aspect ratio while adjusting the width */
max-width: none; /* Allow the image to take its original width */
max-height: none; /* Allow the image to take its original height */
}
A simple solution to achieve desired result is using a
flexbox.Try adding this to your HTML/CSS file:
Here is a fiddle to play around with the code: https://jsfiddle.net/7yuhtfwo/