2016-04-26 89 views
1

我试图创建一个保持居中的UI元素,并且图像缩放到容器的大小。我在图像上添加了标题和文字。但是,当我调整高度或宽度时,图像似乎只在一定范围内按比例缩放。最好只使用CSS和HTML。顶级div需要被绝对定位。我对使用flexbox漠不关心。这只是我尝试过的一个机智。CSS图像调整大小,同时保持成比例

这是一个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>

回答

0

地址:

.imagecontain { 
    max-width: 100%; 
    width: 100% 
} 

删除:

.block { 
    height: 80%; 
} 
+0

这并没有改善任何事情。顺便说一句,我只使用Chrome(Webkit)浏览器。最好用左侧或右侧的图像设置codepen,然后您可以通过移动窗格来调整框的宽度。并通过打开控制台并移动该窗格来调整框的高度。 – furnaceX

相关问题