我想垂直对齐左侧浮动图像右侧的多行文本.
然而
>图像尺寸(高度和宽度)会有所不同,并且事先未知
>文本的长度也各不相同,通常包含多行
>解决方案需要响应以适应不同的屏幕尺寸
>解决方案不应涉及图像,div或其他任何内容的特定px宽度或高度尺寸
>我不想使用表格,因为当图像旁边的文字空间不足时,在某些情况下文本需要放在图像下方
我回顾过以前的问题,但没有什么能与我想要的完全匹配.它需要在任何设备上工作,因此我不能将绝对px值用于任何维度.
我应该如何设计以下样式来实现这一目标?
- <img src="image.jpg" >
- <p>Here is the text that should go to the right of the image</p>
谢谢你的帮助.
解决方法
这将让你开始:
jsFiddle example – 看下面的更好的方法.
基本上,vertical-align:middle和display:inline-block用于p和img元素以进行居中.
HTML
- <div class="element">
- <img src="http://placehold.it/150x150"/>
- <p>Lorem Ipsum is simply dummy text </p>
- </div>
CSS
- .element {
- background:rgb(134,226,255);
- margin:10px;
- }
- p {
- display:inline-block;
- margin:0px;
- width:70%;
- background:white;
- vertical-align:middle;
- }
- img {
- display:inline-block;
- vertical-align:middle;
- }
这是使用display的更好方法:table / display:table-cell相同的HTML ..
jsFiddle example – 半响应… Other jsFiddle example – 响应式img元素..
CSS
- .element {
- width:100%;
- display:table;
- background:rgb(134,255);
- margin:10px 0px;
- padding:10px;
- }
- p {
- display:table-cell;
- height:100%;
- vertical-align:middle;
- background:white;
- }
- img {
- display:table-cell;
- width:100%;
- height:auto;
- }
使用媒体查询的另一个更新
你显然可以使用你想要的任何断点.我使用480px,因为这只是为了举例.尝试调整窗口大小. jsFiddle example
CSS
- @media only screen and (min-width: 480px) {
- .element {
- width:100%;
- display:table;
- background:rgb(134,255);
- margin:10px 0px;
- padding:10px;
- Box-sizing:border-Box;
- -moz-Box-sizing:border-Box;
- -webkit-Box-sizing:border-Box;
- }
- p {
- display:table-cell;
- height:100%;
- vertical-align:middle;
- background:white;
- }
- img {
- display:table-cell;
- width:100%;
- height:auto;
- }
- }
- @media only screen and (max-width: 479px) {
- .element {
- width:100%;
- background:rgb(134,255);
- margin:10px 0px;
- padding:10px;
- Box-sizing:border-Box;
- -moz-Box-sizing:border-Box;
- -webkit-Box-sizing:border-Box;
- }
- p {
- background:white;
- }
- img {
- width:50%;
- margin:0px auto;
- display:block;
- height:auto;
- }
- }