我尝试创建一个保持居中的UI元素,图像缩放到容器的大小。我在图像上有额外的标题和文字。但是当我调整高度或宽度时,图像似乎在一定范围内按比例缩放。最好只使用CSS和HTML。顶级div确实需要绝对定位。我对flexbox的使用漠不关心。这只是我尝试过的一种机智。
这里是codepen。
完整的代码如下所示,尽管在codepen中使用它更容易,因为您可以轻松调整结果窗格。 (打开控制台,这样你也可以调整高度。)
.block {
/* this needs to remain an absolute positioned block with size and location expressed in percent */
position: absolute;
height: 80%;
width: 80%;
top: 10%;
left: 10%;
background-color: #777777;
/* Don't care if using flexbox */
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
align-content: center;
text-align: center;
}
.imagecontain {
position: relative;
padding: 0;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
align-content: center;
}
.image {
max-height: inherit;
max-width: calc(100% - 8px);
padding: 0 !important;
border: 4px solid #123456 !important;
}
.button {
border-color: #b2b2b2;
background-color: #f8f8f8;
color: #444;
position: relative;
display: inline-block;
margin: 0;
padding: 0 12px;
min-width: 52px;
min-height: 47px;
border-width: 1px;
border-style: solid;
border-radius: 2px;
vertical-align: top;
text-align: center;
text-overflow: ellipsis;
font-size: 16px;
line-height: 42px;
cursor: pointer;
box-shadow: 0px 0px 3px #888888 !important;
}
.overimage {
vertical-align: bottom;
position: absolute;
bottom: 10%;
left: 50%;
max-width: 80%;
min-width: 60%;
padding: 5px;
opacity: .7;
transform: translateX(-50%);
background-color: black;
color: white;
border-radius: 10px;
z-index: 2;
}
.name {
text-align: bottom;
background-color: white;
padding: 5px;
border: 1px solid black;
}

<div class="block">
<div class="imagecontain">
<div class="overimage">this is a test of the emergency broadcast</div>
<img class="button image" src="https://scontent-dfw1-1.xx.fbcdn.net/hphotos-xfa1/v/t1.0-9/582520_10151526852434301_1015227082_n.jpg?oh=6537667094d5a160b8fbab0728dc2f5a&oe=57971FCB">
</div>
<div class="name">Mountains</div>
</div>
&#13;
答案 0 :(得分:0)
在CSS中使用background-size属性。将图像从标记更改为div的背景。您正在寻找的具体属性可能是
Page
答案 1 :(得分:0)
添加:
.imagecontain {
max-width: 100%;
width: 100%
}
卸下:
.block {
height: 80%;
}