Javascript 在引导列中垂直居中响应图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27489426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:12:57  来源:igfitidea点击:

Vertically center responsive image in a bootstrap column

javascripthtmlcsstwitter-bootstrapless

提问by user84756

I have reviewed all of the existing questions / answers, and still cannot get a working solution, so I would appreciate any comments on my particular code below.

我已经查看了所有现有的问题/答案,但仍然无法获得有效的解决方案,因此我将不胜感激对我下面的特定代码的任何评论。

I would prefer not to use hard-coded image sizes (pixel counts) in my code, and I am willing to use a combination of Less, CSS, or Javascript in the solution.

我不想在我的代码中使用硬编码的图像大小(像素数),并且我愿意在解决方案中使用 Less、CSS 或 Javascript 的组合。

The image should be centered vertically and horizontally within the Bootstrap column, and remain centered even when the screen is resized.

图像应在 Bootstrap 列中垂直和水平居中,并且即使调整屏幕大小也应保持居中。

My HTML:

我的 HTML:

<div class="container-fluid">
    <div class="container">
    <div class="row">
        <div class="col-md-5">
            <div class="panel">
                Some content
            </div>
        </div>

        <div class="col-md-2">
            <img src="images/myimage.png" class="img-responsive center-block">
        </div>

        <div class="col-md-5">
            <div class="panel>
               Some content
            </div>
        </div>
     </div>
     </div>
 </div>

回答by Patrick

Here's an option using transform:

这是使用转换的选项:

html,body,.container-fluid,.container,.row,.row div {height:100%;;} /* full height for demo purposes */
.vertical-center {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}
.col-md-2 {background-color:#ccc;} /* just to demonstrate the size of column */

http://www.bootply.com/YG8vpg1rIf

http://www.bootply.com/YG8vpg1rIf

回答by Anupam Basak

You can overcome the vertical align problem by using css Flexbox.

Add the class "vertical_center" to the parent div.

Then add the following css

您可以使用 css Flexbox克服垂直对齐问题。

将类“vertical_center”添加到父 div。

然后添加以下css

.vertical_center {
    display: flex;
    align-items: center;
}

回答by Talha Alim

Hope this will solve your problem. Use following CSS property for making the image vertically centered

希望这能解决您的问题。使用以下 CSS 属性使图像垂直居中

img { vertical-align: middle; }

img { vertical-align: middle; }

For horizontal alignment use class name text-centerof bootstrap along with the other class name of your div if yu have. Like,

对于水平对齐,请使用text-centerbootstrap 的类名以及 div 的其他类名(如果有)。喜欢,

<div class="col-md-2 text-center"> ... </div>.

<div class="col-md-2 text-center"> ... </div>.

It will make the content of the div horizontally centered.

它将使 div 的内容水平居中。