在Div中居中对齐图像

时间:2014-07-15 12:02:58

标签: javascript html css layout web

我想将图像集中放在div(fiddle)中。因为我希望div能够继承那个div旁边的另一个div的高度,所以我不得不使用this trick.

出于这个原因,here所描述的解决方案似乎并没有奏效。

要求是没有修改其他行为,但只要获得的效果相同,代码就可以。如果有必要,我也愿意接受涉及javascript的解决方案。

<div class="container"> 
<div class="logo-div">
    <img class="logo" src="http://bit.ly/1qCKrtJ" />
</div>
<div class="text-div">
    <h4 style="display: inline;">Because Sometimes It Takes a Village</h4><br />
    What about robots the size of tea cups that scoot around on tiny wheels, snapping pictures with miniature cameras and keeping track of where they are in relation to dozens of others?
</div>

.container {
    background: green;
    overflow: hidden;
}

.logo-div {
    background: yellow;
    width: 150px;
    float: left;
    padding-bottom: 1000px;
    margin-bottom: -1000px;
}

.text-div {
    background: blue;
    float: left;
    max-width: 350px;
    padding-bottom: 1000px;
    margin-bottom: -1000px;
}

.logo {
    width: 100px;
}

3 个答案:

答案 0 :(得分:2)

我修改了代码,以便徽标图像可以水平和垂直居中对齐。

JSFiddle

HTML code:

<div class="container"> 
    <div class="image-div">
        <div class="logo-div">
            <img class="logo" src="http://bit.ly/1qCKrtJ" />
        </div>
    </div>
    <div class="text-div">
        <h4 style="display: inline;">Because Sometimes It Takes a Village</h4><br />
        What about robots the size of tea cups that scoot around on tiny wheels, snapping pictures with miniature cameras and keeping track of where they are in relation to dozens of others?
    </div>
</div>

Css代码:

.container {
    background: green;
    overflow: hidden;
}

.logo-div {
    background: #FFFF00;
    display: table-cell;
    height: 100px;
    text-align: center;
    vertical-align: middle;
    width: 150px;
}

.text-div {
    background: blue;
    float: left;
    max-width: 350px;
}
.image-div {
    float: left;
}
.logo {
    width: 100px;
}

如果您还有其他问题,请对代码进行评论,然后修改jsfiddle。

问候D.

答案 1 :(得分:0)

如果您只需要水平中心,请尝试:

.logo-div {text-align: center;}
img {margin: 0 auto;}

http://jsfiddle.net/yXNnd/18/


JS版

使用jQuery(我太懒了:))
http://jsfiddle.net/yXNnd/25/

添加此js

$(document).ready(function(){
    var img = $('.logo-div img');
    var top = ($('.container').height() / 2) - (img.height() / 2);
    img.css('margin-top', top + 'px');
});

答案 2 :(得分:0)

这有两种方法。您可以将任何组件的Margin属性设置为'auto',如果您希望它在中间对齐。当然,您可以在CSS中设置此属性,而不是使用样式标记。

<img src="http://bit.ly/1qCKrtJ" style="margin:auto;"/>

另一个是使用中心标签 (因为'margin:auto'可能不适用于某些浏览器的图像,但它适用于div标签。)

<center>
    <img src="http://bit.ly/1qCKrtJ" alt="Logo">
</center>