Html 在 div 内垂直对齐,垂直对齐:中间不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8366053/
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-29 11:48:04  来源:igfitidea点击:

Vertical align inside div, vertical-align: middle not working

htmlcssvertical-alignment

提问by mishap

Vertical-align: middle; is not working.

垂直对齐:中间;不管用。

From css file :
#header {height:150px; text-align: center; vertical-align: middle;}

<div id="header">
    <img alt="" id="logo" src="images/logo.png" />
</div>

I would wrap the logo inside another div if it helps to align it to the center of the wrapper div.

如果有助于将徽标与包装器 div 的中心对齐,我会将徽标包装在另一个 div 中。

采纳答案by Sonal Khunt

You can do this only by padding, because other two ways line-height and vertical-align can't work on img....

你只能通过填充来做到这一点,因为其他两种方式 line-height 和 vertical-align 不能工作img......

Write

#logo
{
padding: 20px 0;
}

20pxcan be anything as you require.

20px可以是您需要的任何东西。

回答by diEcho

do this

做这个

#header {display:table;}
#logo {display:table-cell; vertical-align:middle;}

Reference

参考

回答by coiso

i like doing this:

我喜欢这样做:

<div style="relative">
<img alt="" id="logo" src="images/logo.png" style="position: absolute; top:50%; top-margin:-75px"/>
</div>

回答by Nathan Fox

Another option, although it has its limitations:

另一种选择,尽管它有其局限性:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
   <div style="height:150px; text-align: center;">
      <img src="/centerme.jpg" style="position: relative; top: 50%; margin-top: -25px;" />
   </div>
</body>
</html>

The negative margin should be half of the image height. So the following image will center in the above HTML:

负边距应为图像高度的一半。所以下面的图片将在上面的 HTML 中居中​​:

enter image description here

在此处输入图片说明

This makes the centering dynamic if you happen to have a div that changes height. It can get a little tricky with the relative positioning though, because the image is taken out of the normal layout flow.

如果您碰巧有一个改变高度的 div,这会使居中动态化。但是相对定位可能会有点棘手,因为图像是从正常的布局流程中取出的。

回答by U-DON

#logo {
    position: absolute;
    top: 50%;
    margin-top: -75px;
}

Common method of doing vertical alignment. With top being 50% and margin-top being negative half the dimension of the parent div.

做垂直对齐的常用方法。top 为 50%,margin-top 为父 div 尺寸的负一半。

回答by Nirman

i dont know why it worked in my case... but by I could see it working by doing following:

我不知道为什么它在我的情况下有效......但是我可以通过执行以下操作来看到它的工作:

div {padding-top: 0%;}