【问题标题】:How do I vertically centre an image of known dimensions inside a div (with variable height) having dynamic content? [duplicate]如何在具有动态内容的 div(高度可变)内垂直居中已知尺寸的图像? [复制]
【发布时间】:2014-07-17 19:43:26
【问题描述】:
<div class="col-md-3 image-container">
    <img class="image" src="path-to-my-image">
</div>
<div class="col-md-9 dynamic-text-container">
    <p><!-- Dynamic text here --></p>
</div>

我在我的项目中使用 bootstrap 3。如何在具有可变高度的 div 内垂直居中图像(使用 CSS 表格居中)? 这是一个演示: http://www.bootply.com/7rSVv7uDBu

【问题讨论】:

  • 您是否尝试过四处搜索?我看到这个问题太多了!
  • 是的。过去 3 天我一直在做同样的事情,但没有运气......即使是 Chris Coyier 也无法给我答案。
  • 有很多方法可以做到这一点,请四处搜索。另外,如果您觉得这是一个以前从未被问过的问题,为什么不设置一个演示供人们查看和使用呢?注意:你可以只使用position: absolute; - Look here
  • 看看这个,SO中还有很多其他的例子......stackoverflow.com/questions/7273338/…
  • “即使 Chris Coyier 也无法给我答案” - 有趣...我不记得在 CSS-Tricks 论坛上看到过这个问题。

标签: html css centering


【解决方案1】:

Jsfiddle Demo

修改后的 CSS

.card{ 
  display:table; 
} 
.image-container,
.dynamic-text-container{ 
  display:table-cell; 
  vertical-align:middle; 
}

.image-container {
    width:25%; /* or some other value */
}


.image-container img {
    display: block;
    margin:0 auto;
}

【讨论】:

    【解决方案2】:

    看看这个:

    HTML:

    <div class="col-md-3 image-container">
        <img class="image" src="image.png" height="200px;" width="200px" />
    </div>
    <div class="col-md-9 dynamic-text-container">
        <p>Some text....</p>
    </div>
    

    CSS:

    .image-container {
        height: 600px;
        text-align: center;
    }
    .image {
        position: relative;
        top: 50%;
        margin-top: -100px; /* half of image height */
    }
    

    DEMO HERE

    【讨论】:

    • @Ruddy;感谢您的回答,但请看,这不是我需要的固定高度问题。
    猜你喜欢
    • 2015-08-05
    • 2010-09-08
    • 2014-05-26
    • 1970-01-01
    • 2015-06-01
    • 2016-01-19
    • 2011-07-21
    • 1970-01-01
    • 2012-12-08
    相关资源
    最近更新 更多