2016-07-07 28 views
0

所以我有一個div,其高度我最初不知道。它有兩個孩子 - 左側爲<img><div>包含右側的一些內容。圖像大小是固定的,例如50乘50。但是,內容可以是任何大小。甚至可能只有一行,在這種情況下,與照片相比,它的尺寸變小了。無論哪種方式,父div必須找出哪一個更大,並垂直增長以適應兩者,同時確保兩者都正確居中(考慮垂直填充5 px)。垂直對齊圖像與動態文本

也想象一下,內容不會包裹在圖像下方,即它是右側的獨立元素(就像是浮動的右側)。

也就是說,如果內容只是說一行,那麼父div應該是高度50 + 5 * 2 = 60px,左邊的img從頂部5px居中,右邊的內容(假設在距離左邊5px處),這裏只是一條垂直居中的線。

或者說內容太大,它是100px高,那麼父div將是100 + 5 * 2 = 110px高。 img將位於頂部30px的左側。

任何人都可以幫我解決這個問題嗎?

這是我想出了:https://jsfiddle.net/fj77eobe/

.elem-option { 
 
    text-align: left; 
 
    white-space: nowrap; 
 
    width: 300px; 
 
    background: pink; 
 
} 
 
/* The ghost, nudged to maintain perfect centering */ 
 
.elem-option:before { 
 
    content: ''; 
 
    display: inline-block; 
 
    height: 100%; 
 
    vertical-align: middle; 
 
    margin-right: -0.25em; 
 
} 
 
/* The element to be centered, can also be of any width and height */ 
 
.elem-photo { 
 
    display: inline-block; 
 
    vertical-align: middle; 
 
    width: 40px; 
 
    height: 40px; 
 
    margin-left: 10px; 
 
} 
 
.elem-content { 
 
    display: inline-block; 
 
    margin-left: 5px; 
 
    width: 100px; 
 
    word-wrap: break-word; 
 
    overflow: none; 
 
}
<div class='elem-option'> 
 
    <img src="https://img.zmtcdn.com/data/reviews_photos/b22/28f633be81fd340785c3af7f7858cb22_1463913069.jpg" class="elem-photo" /> 
 
    <div class='elem-content'> 
 
    Amader ekhane ekjon er heavy khar chhilo...take paedo bole khepano hoto..toh se ajkal ei defense deyAmader ekhane ekjon er heavy khar chhilo...take paedo bole khepano hoto..toh se ajkal ei defense deyAmader ekhane ekjon er heavy khar chhilo...take paedo 
 
    bole khepano hoto..toh se ajkal ei defense deyAmader ekhane ekjon er heavy khar chhilo...take paedo bole khepano hoto..toh se ajkal ei defense dey 
 
    </div> 
 
</div>

回答

1

嘗試將容器設置爲display: flex;​​

.elem-option { 
 
    display: flex; 
 
    align-items: center; 
 
    padding: 5px; 
 
    background: pink; 
 
} 
 
.elem-photo { 
 
    margin-right: 5px; 
 
    flex: 0 0 50px; 
 
    height: 50px; 
 
}
<div class='elem-option'> 
 
    <img src="//unsplash.it/200" class="elem-photo" /> 
 
    <div class='elem-content'> 
 
    Lorem ipsum dolor sit amet. 
 
    </div> 
 
</div> 
 

 
<br> 
 

 
<div class='elem-option'> 
 
    <img src="//unsplash.it/200" class="elem-photo" /> 
 
    <div class='elem-content'> 
 
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident. 
 
    </div> 
 
</div>