将图像垂直居中在div的div内

时间:2016-05-12 01:55:09

标签: javascript html css twitter-bootstrap-3

这就是我目前所拥有的:

            <div class="col-lg-10 col-lg-offset-1 text-center">
                <h2>Title</h2>
                <hr class="small">
                <div class="row">
                    <div class="col-md-6" id="logo">
                        <div class="portfolio-item">
                            <img class="img-portfolio img-responsive" src="logo.jpg">
                        </div>
                    </div>
                    <div class="col-md-5" id="description">
                        <div class="portfolio-item">
                              Text
                        </div>
                    </div>
                </div>

我希望能够将图像置于左侧列中心,但我不确定如何。我试图在这里遵循这个,但它没有正常工作。 How to vertically align an image inside div

3 个答案:

答案 0 :(得分:1)

试试这个:

http://codepen.io/tiagofabre/pen/LNagaB

此链接还有关于flex的一篇很酷的文章:

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

.vertical-center {
  min-height: 100%;
  min-height: 100vh; 

  display: flex;
  align-items: center;
}
<div class="col-lg-10 col-lg-offset-1 text-center">
  <h2>Title</h2>
  <hr class="small">
  <div class="container-fluid col-md-6 vertical-center">
    <div class="col-sm-12 bg-green">
      <img class="img-responsive center-block" src="http://placeimg.com/100/100/animals" />
    </div>
  </div>
  <div class="container-fluid col-md-6 vertical-center">
    <div class="col-sm-12 bg-green">
      <div class="portfolio-item">Text</div>
    </div>
  </div>
</div>

答案 1 :(得分:0)

进入父div,添加此类:

col-lg-6 col-lg-push-6
像这样:

<div class="col-lg-6 col-lg-push-6" id="logo">
    <div class="portfolio-item">
        <img class="img-portfolio img-responsive" src="logo.jpg">
    </div>
</div>

答案 2 :(得分:0)

您可以将portfolio-item位置设置为相对,将img设置为绝对位置,并为图片top: 50%; transform: translateY(-50%) https://jsfiddle.net/pu4L80gq/

此外,您可以使用JS来确定图像容器高度和图像高度,以便margin-top为容器提供图像或padding-top

(图像容器高度 - 图像高度)将为您提供容器中的剩余空间,然后将其分为两个,使用此值可以使图像垂直居中https://jsfiddle.net/pu4L80gq/1/

$(document).ready(function () {
    var imgContHeight = $('.img-container').height();
    var image = $('.img-container img');
    var imgHeight = image.height();

    image.css({
        marginTop: (imgContHeight - imgHeight) / 2
    });
});