html – 垂直对齐浮动图像右侧的文本,图像大小不同,响应迅速

前端之家收集整理的这篇文章主要介绍了html – 垂直对齐浮动图像右侧的文本,图像大小不同,响应迅速前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想垂直对齐左侧浮动图像右侧的多行文本.

然而

>图像尺寸(高度和宽度)会有所不同,并且事先未知
>文本的长度也各不相同,通常包含多行
>解决方案需要响应以适应不同的屏幕尺寸
>解决方案不应涉及图像,div或其他任何内容的特定px宽度或高度尺寸

>我不想使用表格,因为当图像旁边的文字空间不足时,在某些情况下文本需要放在图像下方

我回顾过以前的问题,但没有什么能与我想要的完全匹配.它需要在任何设备上工作,因此我不能将绝对px值用于任何维度.

我应该如何设计以下样式来实现这一目标?

  1. <img src="image.jpg" >
  2.  
  3. <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

  1. <div class="element">
  2. <img src="http://placehold.it/150x150"/>
  3. <p>Lorem Ipsum is simply dummy text </p>
  4. </div>

CSS

  1. .element {
  2. background:rgb(134,226,255);
  3. margin:10px;
  4. }
  5. p {
  6. display:inline-block;
  7. margin:0px;
  8. width:70%;
  9. background:white;
  10. vertical-align:middle;
  11. }
  12. img {
  13. display:inline-block;
  14. vertical-align:middle;
  15. }

这是使用display的更好方法:table / display:table-cell相同的HTML ..

jsFiddle example – 半响应… Other jsFiddle example – 响应式img元素..

CSS

  1. .element {
  2. width:100%;
  3. display:table;
  4. background:rgb(134,255);
  5. margin:10px 0px;
  6. padding:10px;
  7. }
  8. p {
  9. display:table-cell;
  10. height:100%;
  11. vertical-align:middle;
  12. background:white;
  13. }
  14. img {
  15. display:table-cell;
  16. width:100%;
  17. height:auto;
  18. }

使用媒体查询的另一个更新

你显然可以使用你想要的任何断点.我使用480px,因为这只是为了举例.尝试调整窗口大小. jsFiddle example

CSS

  1. @media only screen and (min-width: 480px) {
  2. .element {
  3. width:100%;
  4. display:table;
  5. background:rgb(134,255);
  6. margin:10px 0px;
  7. padding:10px;
  8. Box-sizing:border-Box;
  9. -moz-Box-sizing:border-Box;
  10. -webkit-Box-sizing:border-Box;
  11. }
  12. p {
  13. display:table-cell;
  14. height:100%;
  15. vertical-align:middle;
  16. background:white;
  17. }
  18. img {
  19. display:table-cell;
  20. width:100%;
  21. height:auto;
  22. }
  23. }
  24. @media only screen and (max-width: 479px) {
  25. .element {
  26. width:100%;
  27. background:rgb(134,255);
  28. margin:10px 0px;
  29. padding:10px;
  30. Box-sizing:border-Box;
  31. -moz-Box-sizing:border-Box;
  32. -webkit-Box-sizing:border-Box;
  33. }
  34. p {
  35. background:white;
  36. }
  37. img {
  38. width:50%;
  39. margin:0px auto;
  40. display:block;
  41. height:auto;
  42. }
  43. }

猜你在找的HTML相关文章