具有多个内容的div的垂直居中(img和包装文本)

时间:2011-01-28 09:40:52

标签: css html image textwrapping vertical-alignment

我想显示div中列出的小盒子。每个盒子都有固定的宽度和高度,里面有一个img和一些文字(图像就像图标,它们的宽度和高度相同)。与旁边的文字相比,图标非常大,所以我想将它们垂直居中放置。

现在,我的代码如下所示:

<div class="hbutton">
    <div class="hwrap">
        <img style="vertical-align:middle; float:left;" height="40" src="icon.png" width="40" />
        <span>Some very long text displayed in the box.</span>
    </div>
</div>

为了使hwrap div居中,我使用了this trick。没有其他div,没有其他设置。

居中本身工作正常,但如果我在img附近放一个长文本,但它不适合,文本开始包装,但第二行从图像开始,而不是在第一行下面。

我想看到什么:
enter image description here

我所看到的是:
enter image description here

我也尝试将文本放入div并更改属性,但我无法使其工作。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

这不一定是 easy ,但以下似乎可以实现您的目标(请记住,我将文本元素从span更改为p,个人/语义原因):

HTML:

<div class="hbutton">
    <div class="hwrap">
        <img height="40" src="icon.png" width="40" />
        <p>Some very long text displayed in the box.</p>
    </div>
</div>

的CSS:

.hbutton {
    width: 50%;
    margin: 0 auto 1em auto;
}

.hwrap {
    position: relative;
    /* the following is just for aesthetic reasons, amend to taste */
    border: 1px solid #ccc; 
    border-radius: 1em;
    padding: 0.5em;
}

p {
    margin: 0 0 0 50px;
}

img {
    position: absolute;
    top: 50%;
    left: 0.5em; /* adjust to taste, this is just for aesthetic reasons */
    margin-top: -20px;
    height: 40px;
    width: 40px;
}

JS Fiddle demo

答案 1 :(得分:0)

修改

<div class="hbutton">
    <div class="hwrap">
        <img style="vertical-align:middle; float:left;" height="40" src="icon.png" width="40" />
        <span>Some very long text displayed in the box.</span>
    </div>
</div>

使用相同的标记,我会添加以下CSS属性:

.hwrap {
    position : relative; // any type of positioning will work, but one must be declared
}
.hwrap span {
    position : absolute;
    margin-left : 50px // {icon width} + 10px for padding
}

这样,跨度本身就没有理由远远超过...你可以根据自己的喜好添加所需的其他任何定位 - 但你应该明白这一点。

编辑:我刚才注意到这种方法几乎与David Thomas的方法相同。 1。

答案 2 :(得分:0)

我找到了解决问题的完美方法under this link

它可以正确地使用单行和多行文本进行垂直居中,无需任何解决方法,并且没有指数级的div!