img
是嵌入式元素,而.text-container
是嵌入式块。当内联元素无法放入当前行时,行会中断,并且元素将移至下一行。
为了防止在.container
上设置white-space: nowrap
。要启用.text-container
中的包装,请定义其宽度,并将空白行为恢复为普通(换行)。
.container {
width: 200px;
margin-bottom: 10px;
border: 1px solid red;
white-space: nowrap; /** force the elements to stay side by side **/
}
img {
height: 50px;
width: 50px;
border-radius: 50%;
border: 1px solid black;
vertical-align: middle
}
.text-container {
display: inline-block;
width: calc(100% - 60px); /** containers width - img width - margin-left **/
margin-left: 10px;
white-space: normal;
vertical-align: middle
}
<div class="container">
<img src="http://4.bp.blogspot.com/-e98D9RG3Gzs/U5XAgtaj9tI/AAAAAAAAIIo/hDPgyrWvxy0/s1600/shy-smiley.png" />
<div class="text-container">I AM TEXT</div>
</div>
<div class="container">
<img src="http://4.bp.blogspot.com/-e98D9RG3Gzs/U5XAgtaj9tI/AAAAAAAAIIo/hDPgyrWvxy0/s1600/shy-smiley.png" />
<div class="text-container">I AM TEXT OH NOOO</div>
</div>
但是,你甚至可以进一步利用Flexbox,就与align-items: center
简化结构:
.container {
display: flex; /** set the container as flexbox **/
align-items: center; /** align all items vertically **/
width: 200px;
margin-bottom: 10px;
border: 1px solid red;
}
img {
height: 50px;
width: 50px;
border-radius: 50%;
border: 1px solid black;
}
.text-container {
margin-left: 10px;
}
<div class="container">
<img src="http://4.bp.blogspot.com/-e98D9RG3Gzs/U5XAgtaj9tI/AAAAAAAAIIo/hDPgyrWvxy0/s1600/shy-smiley.png" />
<div class="text-container">I AM TEXT</div>
</div>
<div class="container">
<img src="http://4.bp.blogspot.com/-e98D9RG3Gzs/U5XAgtaj9tI/AAAAAAAAIIo/hDPgyrWvxy0/s1600/shy-smiley.png" />
<div class="text-container">I AM TEXT OH NOOO</div>
</div>
,并通过使用Flexbox的,你也可以将带有边框的图像移动到的背景获得单个div解决方案。
.container {
display: flex; /** set the container as flexbox **/
align-items: center; /** align all items vertically **/
box-sizing: border-box; /** the padding and the border are part of the width **/
width: 202px;
min-height: 54px;
margin-bottom: 10px;
padding-left: 60px; /** save space for the image and the margin between the image and the text **/
border: 1px solid red;
/** set the image and the image border as backgrounds **/
background: radial-gradient(circle at center, transparent 0, transparent 24px, black 24px, transparent 26px), url(http://4.bp.blogspot.com/-e98D9RG3Gzs/U5XAgtaj9tI/AAAAAAAAIIo/hDPgyrWvxy0/s1600/shy-smiley.png);
/** set the backgrounds size **/
background-size: 51px 51px, 50px 50px;
background-repeat: no-repeat; /** prevent the backgrounds from repeating themselves to fill the container **/
background-position: left center; /** position them in relation to the container **/
}
<div class="container">
I AM TEXT
</div>
<div class="container">
I AM TEXT OH NOO
</div>
这是为了满足 “垂直居中” 的要求是唯一的答案。好工作。 –