0

问题

我希望图像在文本旁边居中。每个框中的文本数量会有所不同,所以我无法设置高度。因为我研究人们主要使用两种垂直居中方式。使用 line-height 我可以'不使用,因为我没有固定高度。第二个是使用我不能使用的绝对定位,因为里面有图像的左 div 会覆盖文本。如果我将填充设置为文本,当图像不存在时不会好看。

我能想到的最好的方法是使用jQuery来获取和设置容器高度,然后根据高度设置边距。

<div class="container">
        <div class="image_holder">
            <img src="http://blog.oxforddictionaries.com/wpcms/wp-content/uploads/cat-160x160.jpg" alt="cat" />
        </div>

        <p>text</p>
    </div>

    <style type="text/css">
        .container {
            width:600px;
            overflow:hidden; }
        .image_holder {
            width:100px;
            height:100%;
            float:left;
            background:#eaf0ff; }
        p {
            width:500px;
            float:left; }
    </style>

    <script>

        $('.container').css('height', $('.container').height() );

        $('.image_holder').css('margin-top', ( $('.container').height() - $('.image_holder img').height() ) / 2 );

    </script>

有没有办法用纯 CSS 干净地做到这一点?

4

1 回答 1

0

我想出的最佳解决方案是将图片绝对定位在框中,然后如果框中没有图像,则使用 javascript 删除填充。

于 2012-06-26T13:30:44.367 回答