2016-07-07 52 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>