2016-04-26 229 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

相關問題