我有一个页面,其中我根据图像所属的类别并排显示图像,每个图像数组都以其所属的类别开头。图片的宽度和高度各不相同,但都放在一个绝对高度为 330 像素的 div 中。
CSS:
.front-index {
margin: 0 1em 0 2em;
}
.front-work {
margin: 0 2em 2em 0;
display: table;
width: 66px;
position: relative;
height: 330px;
background-color:#f0f0f0;
}
.front-work img {
margin: .3em 0 .3em 0;
}
.wraptocenter {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.wraptocenter * {
vertical-align: middle;
}
.front-index,
.front-work {
float: left;
}
HTML:
<div class="front-index"><p>How to get<br /> this text on the same line with<br /> yellow image on the right?</p></div>
<div class="front-work">
<div class="wraptocenter">
<img width="162" height="250" src="http://images.fanpop.com/images/image_uploads/Yellow-Wallpaper-yellow-646738_800_600.jpg"/>
</div>
</div>
<div class="front-work">
<div class="wraptocenter">
<img width="250" height="166" src="http://www.takenseriouslyamusing.com/wp-content/uploads/2012/08/Blue.png"/>
</div>
</div>
…
JSFIDDLE:http://jsfiddle.net/rCAKa/9/
我想将文本与右侧第一张图片对齐到同一行。
我的想法是,也许这应该在 jquery 中完成。 IE。以某种方式测量 .front-work div 中距顶部的图像距离,然后将该值作为内联代码分配给 .front-index div(顶部:任意 px)。
也许你们中有人遇到过此类问题并且知道解决此类问题的方法? CSS 或 JS。
最佳答案
以我的拙见,我不认为你正在做的事情是通过 CSS 实现的——它需要一些简单的 JavaScript 技巧,因为你必须知道第一个图像的相对位置(从容器的顶部开始)放置文本的正确位置 - CSS 并非为此而设计。
JS 中的策略是:
- 遍历每个包含您要放置的文本的元素
- 获取第一个图像向右的垂直顶部偏移量(相对于包含的父图像)
将顶部填充匹配到图像的顶部位置。或者,您可以设置子元素的顶部位置、填充或边距,或通过其他方式重新定位文本。
$(document).ready(function() { $(".front-index").each(function() { var fromTop = $(this).next().find("img").position().top; $(this).css({ "padding-top":fromTop }); }); });
我已经 fork 了你的 fiddle ,你可以在这里看到它的实际效果 - http://jsfiddle.net/teddyrised/LT54V/1/
p/s:在相关说明中,.wraptocenter * { }
可能不是最好的(最有效的)选择器,因为如果元素中有很多子元素(他们可能有或可能有更多的子元素),CSS 将不得不遍历所有这些子元素。相反,请尝试使用 .wraptocenter > * { }
或仅使用 .wraptocenter img { }
:)
关于javascript - 将 div 与第一个垂直居中的 div 对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15040385/