简体   繁体   English

如何在引导程序中的div内垂直居中放置图像?

[英]How can I center an image vertically inside a div in bootstrap?

In the first section have a p and an image. 在第一部分中有一个p和一个图像。 I would really like to know how to center them vertically. 我真的很想知道如何将它们垂直居中。

<section id="banner">
    <div class="container text-center">
        <div class="row">
            <div class="col-md-6">
                <p class="promo-title">Incubamos tus ideas para dar vida a tus sueños</p>
                <a href="#" class="btn btn-primary btn-lg active" role="button" aria-pressed="true">Lorem</a>
            </div>
            <div class="col-md-6 text-center">
                <img src="https://cdn.pixabay.com/photo/2017/08/18/00/23/computer-2653374_960_720.png" class="img-fluid" alt="">
            </div>
        </div>
    </div>
</section>

You can try this 你可以试试这个

<div class="col-md-6 d-flex justify-content-center align-middle">
     <img src="https://cdn.pixabay.com/photo/2017/08/18/00/23/computer-2653374_960_720.png" class="img-fluid" alt="">
</div>

You could try adding: 您可以尝试添加:

p, img {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

Copied from here 从这里复制

You need flexbox. 您需要flexbox。

<div class="col-md-6 d-flex flex-column align-items-center">
  <p class="promo-title">Incubamos tus ideas para dar vida a tus sueños</p>
  <a href="#" class="btn btn-primary btn-lg active" role="button" aria-pressed="true">Lorem</a>
</div>

In bootstrap there are easy classes you can add that will configure any element into the flex container you need. 在引导程序中,可以添加一些简单的类,这些类将在所需的flex容器中配置任何元素。 It is very important to note that flexbox properties affect the flex container and the immediate child elements which become flex elements. 请务必注意,flexbox属性会影响flex容器和成为flex元素的直接子元素。

Add this class to the div that wraps the image and paragraph you want to have centered: 将此类添加到div ,该wr包装您要居中的图像和段落:

d-flex

That adds display: flex to the element and turns it into a flex container! 这就增加了display: flex到元素并将其变成flex容器!

To have the flex items (the direct child elements) layout in a column, add this: 要在列中包含弹性项目(直接子元素)布局,请添加以下内容:

flex-column

That adds flex-direction: column to the element. 这会将flex-direction: column到元素。

Finally, you need to center them, add: 最后,您需要将它们居中,然后添加:

align-items-center

That adds align-items: center . 这增加了align-items: center It really helps to understand each of these properties do but if you add all 3 you will get the desired layout. 确实有助于理解这些属性中的每一个,但是如果将所有3个属性相加,将获得所需的布局。 More reading: 更多阅读:

Bootstrap flex docs: https://getbootstrap.com/docs/4.0/utilities/flex/ Bootstrap Flex文档: https : //getbootstrap.com/docs/4.0/utilities/flex/

My fav Flexbox resource: https://css-tricks.com/snippets/css/a-guide-to-flexbox/ 我最喜欢的Flexbox资源: https ://css-tricks.com/snippets/css/a-guide-to-flexbox/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM