我一直在努力开发一个网站,其中包含标题和正文中的图像。然而,我在尝试将图像置于身体部分的中心时遇到了挑战。图像顽固地保持在左侧,拒绝移动。
您可以在 GitHub 上找到我的项目的代码。
最初,我做了以下调整:
height: 100vh;
添加到 .grid
类中,旨在使其占据整个视口高度。text-align: center;
应用于 .grid div
,以便在每个网格项目中集中内容。max-width: 100%;
中添加了 max-height: 100%;
和 #plattegrond
,以防止图像超出容器尺寸。尽管我期望将图像水平居中于页面中间,但结果却出乎意料。图像变小了,这不是我的本意,但它确实水平居中。然而,它却顽固地留在了网站的左侧,未能在页面中间垂直居中。
为了找到解决方案,我做了额外的更改:
.grid
类的显示属性更改为 flex
,以便更轻松地将子元素居中。justify-content: center;
和align-items: center;
即可实现水平居中和垂直居中。#plattegrond
的宽度和高度属性以填充容器,同时保持原始纵横比。不幸的是,结果并没有达到预期。图像居中,但它变得太大,导致链接到同一样式表的其他页面出现问题。这对保持整个网站的大小一致提出了意想不到的挑战。
对于这项任务,我向 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 */
}
实现所需结果的一个简单解决方案是使用
flexbox
。
尝试将其添加到您的 HTML/CSS 文件中:
<div class="img-container">
<img class="center" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_light_color_272x92dp.png" />
</div>
.img-container {
display: flex;
justify-content: center;
align-items: center;
}
.center {
width: 50%;
}
这里有一个可以使用代码的小提琴:https://jsfiddle.net/7yuhtfwo/