我正在处理一个包含 2 个 div block 的网页,它们的宽度均为 50%。左边是文字,右边是图片。两个内容都集中在 div block 的中间。使用 CSS 到目前为止,当我调整浏览器窗口大小时,图像也会调整大小。但只有当我调整宽度时它才会这样做。如果我只调整高度,图像大小不会改变。它只是保持不变。这会导致图像溢出。但是,至少在达到最小高度之前,我希望图像大小也能对浏览器高度使用react。
为了说明我的意思,我将右侧 div block 的背景色设为白色,并调整了浏览器窗口的大小。这是完整窗口大小的样子:
现在有一个小窗口宽度:
并且窗口高度较小:
CSS 代码
<style type="text/css">
html, body {
height: 100%;
padding: 0;
margin: 0;
background-color: black;
}
.half-window-left {
width: 50%;
height: 100%;
float: left;
background-color: black;
display: flex;
justify-content: center;
}
.title {
margin: 0 auto;
align-self: center;
font-family: "Optima", Arial, sans-serif;
font-size: 60px;
color: white;
}
.half-window-right {
width: 50%;
height: 100%;
float: right;
background-color: white;
display: flex;
justify-content: center;
overflow: hidden;
}
.div-hexagon-center {
left: -10%;
width: 50%;
height: auto;
margin: 0 auto;
align-self: center;
position: relative;
display: flex;
object-fit: contain;
background-color: black;
overflow-y: hidden;
}
img {
display: block;
min-width: 30%;
width: 100%;
height: auto;
}
</style>
HTML 代码
<div class="half-window-left">
<table class="title">
<tr>
<td><b style="color: #62B7F4;">W</b>ater</td>
</tr>
<tr><td> </td></tr>
<tr>
<td><b style="color: #31D994;">B</b>iosphere</td>
</tr>
<tr><td> </td></tr>
<tr>
<td><b style="color: #DAC081;">E</b>arth</td>
</tr>
</table>
</div>
<div class="half-window-right">
<div class="div-hexagon-center">
<img src="tripple-hexagon.png"/>
</div>
</div>
我想我也搞砸了 CSS 代码,因为周围有太多测试。有许多可能的解决方案,我尝试了其中的大部分,但没有取得太大成功。
最佳答案
如果您希望图像的高度响应屏幕的高度,您可以在图像上设置百分比高度,设置最大和最小高度,这样图像就不会变得太大或太小。像这样:
html {
height: 100%;
}
body {
margin: 0;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.img {
background-size: cover;
background-image: url(https://www.w3schools.com/w3css/img_lights.jpg);
width: 100%;
max-width: 400px;
min-width: 200px;
height: 100%;
max-height: 400px;
min-height: 200px;
}
<div class='img'>
</div>
我使用了带有背景图像的 div,因此我也可以使用设置为“cover”的 background-size css 属性,但这取决于您是否需要。此外,您还需要使用百分比和最大值/最小值来满足您的需求
关于html - CSS随窗口高度的变化调整图像高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59183075/