Html 垂直对齐 div(无表格)

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

Vertically align div (no tables)

htmlcssalignment

提问by JonH

I can horizontally align a div and all the content looks nice. Looking to vertical align a div that does not contain any tables. I tried setting margin positions to some negative values inside of the #container but that sort of worked. I know CSS isn't supporting this yet?

我可以水平对齐一个 div,所有的内容看起来都不错。希望垂直对齐不包含任何表格的 div。我尝试在 #container 内将保证金头寸设置为一些负值,但这种方法有效。我知道 CSS 还不支持这个?

Here is my markup:

这是我的标记:

body
{
    background: #777; /* gray */
    text-align: center;
}

#container 
{ 
    margin: 0 auto;
    width: 968px;
    text-align: left;
}

#toptab
{
    background: #f77; /* red */
    height: 14px;
    width: 968px;
}

#middletab
{
    background: #7f7; /* green */
    width: 968px;
}

#data
{
    width: 948px; /* 948 for the box plus we need 20 more px to handle the padding */
    padding-left: 10px; 
    padding-right 10px;
}

#bottomtab
{
    background: #77f; /* blue */
    height: 14px;
    width: 968px;
}
<div id="container">
    <div id="toptab"></div>
    <div id="middletab">
        <div id="data">
            The quick brown fox jumped over the big red bear.
            The quick brown fox jumped over the big red bear.
            The quick brown fox jumped over the big red bear.
            The quick brown fox jumped over the big red bear.
            The quick brown fox jumped over the big red bear.
            The quick brown fox jumped over the big red bear.
            The quick brown fox jumped over the big red bear.
            The quick brown fox jumped over the big red bear.
            The quick brown fox jumped over the big red bear.
            The quick brown fox jumped over the big red bear.
            The quick brown fox jumped over the big red bear.
            The quick brown fox jumped over the big red bear.
        </div>
    </div>
    <div id="bottomtab"></div>
</div>

Run the snippet above and click "full page" to see how it currently looks. Basically, it looks great horizontally, but now I need it to also center vertically in the page.

运行上面的代码段并单击“整页”以查看它当前的外观。基本上,它在水平方向上看起来很棒,但现在我还需要它在页面中垂直居中。

The element that I want to align vertically is the #container div. The effect would force the entire div and all sub divs to not only be horizontally aligned but also vertically. I know this is possible and I know Andy Budd posted such a solution but it doesn't seem to work for me.

我想要垂直对齐的元素是#container div。该效果将强制整个 div 和所有子 div 不仅水平对齐,而且垂直对齐。我知道这是可能的,我知道 Andy Budd 发布了这样一个解决方案,但它似乎对我不起作用。

回答by Corey Ballou

Unless you have the ability to explicitly set the height of your container (which doesnt look like that's the case), there is no cross browser solutionfor vertically centering your DIV container.

除非您能够明确设置容器的高度(看起来并非如此),否则没有用于垂直居中 DIV 容器的跨浏览器解决方案

Using a table is completely viable, but you have noted that this cannot be used.

使用表格是完全可行的,但您已经注意到不能使用它。

If javascript is an option, we could easily remedy this for you. A jQuery plugin already exists for vertically aligning a container.

如果 javascript 是一个选项,我们可以很容易地为您解决这个问题。已经存在用于垂直对齐容器的 jQuery 插件。

(function ($) {
    // VERTICALLY ALIGN FUNCTION
    $.fn.vAlign = function() {
        return this.each(function(i){
            var ah = $(this).height();
            var ph = $(this).parent().height();
            var mh = (ph - ah) / 2;
            $(this).css('margin-top', mh);
        });
    };
})(jQuery);

And you would vertically align a DIV block like so:

您可以像这样垂直对齐 DIV 块:

$('#example').vAlign();

Taken from Simple Vertical Align Plugin.

取自简单的垂直对齐插件

回答by Gregory Pakosz

Have a look at Vertical Centering With CSSor Vertically center content with CSSor CSS Vertical Centering. Method 3 of first reference is the same as CSS vertical center using float and clear.

查看使用 CSS 垂直居中使用 CSSCSS 垂直居中垂直居中内容。第一个参考的方法 3 与使用 float 和 clear 的 CSS 垂直居中相同。

And it's surely a good idea to test the result with a service like browsershots.org

使用像browsershots.org这样的服务来测试结果肯定是个好主意



EDIT: I modified your CSS and markup to implement Method 3:

编辑:我修改了你的 CSS 和标记来实现方法 3:

css:

css:

* {
  margin:0;
  padding:0;
}

html,
body {
  height: 100%;
}

body {
  text-align:center;
}

#floater {
  float: left;
  height:50%;
  margin-bottom: -100px;
}

#container
{
  clear:both;
  position: relative;
  margin: 0 auto;
  width:968px;
  text-align: left;
  height: 200px;
}

...

markup:

标记:

<body>
<div id="floater"></div>
<div id="container">

...

The drawback I see in this method is that with CSS you have to know in advance the height of your content, so that you can apply a negative margin of half this height to the floater. In the example I chose 200px.

我在这种方法中看到的缺点是,使用 CSS 时,您必须提前知道内容的高度,以便您可以将这个高度一半的负边距应用于浮动内容。在示例中,我选择了200px.

See it in action.

看到它在行动

回答by Peter Di Cecco

There are a few ways to do this, all with compromises.

有几种方法可以做到这一点,但都需要妥协。

  • Use position:absolute, a fixed height, and overflow:auto.
  • Use display:table, display:table-cell, and vertical-align:middle
  • Use javascript
  • 使用position:absolute、固定高度和overflow:auto
  • 使用display:table, display:table-cell, 和vertical-align:middle
  • 使用 JavaScript

I think option #2 is pretty good.

我认为选项#2 非常好。

edit:I don't think option 2 will work in IE. You may be stuck with javascript if you want to keep the height dynamic.

编辑:我认为选项 2 在 IE 中不起作用。如果你想保持高度动态,你可能会被 javascript 卡住。

回答by BalusC

With pure CSS, this is onlypossible if the div has a fixedheight. You can then positionit absoluteand set its topand leftto 50%and the margin-topand margin-leftto the negative half of its widthand heightrespectively.

使用纯 CSS,只有当 div 具有固定的height. 然后,您可以positionabsolute并设置其topleft50%margin-topmargin-left它的负半widthheight分别。

Here's an SSCCE, just copy'n'paste'n'run. The border is purely presentational, the remaining styles are required.

这是一个SSCCE,只需复制'n'paste'n'run。边框纯粹是展示性的,其余的样式是必需的。

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 1909753</title>
    </head>
    <style>
        #content {
            position: absolute;
            width: 300px;
            height: 200px;
            top: 50%;
            left: 50%;
            margin-left: -150px; /* Negative half of width. */
            margin-top: -100px; /* Negative half of height. */
            border: 1px solid #000;
        }
    </style>
    <body>
        <div id="content">
            content
        </div>
    </body>
</html>

If there is no means of a fixed height, then you'll need to grasp Javascript and live with the fact that client will see the div quickly being shifted to middle during page load, which might cause a "wtf?" experience.

如果没有固定高度的方法,那么您需要掌握 Javascript 并接受这样一个事实,即客户端会在页面加载过程中看到 div 快速移动到中间,这可能会导致“wtf?” 经验。

回答by andy magoon

Make a container div with style display: tableand use the style vertical-align: topon inner elements that are display: inline-block

制作一个带有样式的容器 divdisplay: tablevertical-align: top在内部元素上使用该样式display: inline-block

Working demo at http://jsfiddle.net/uzcrt/

http://jsfiddle.net/uzcrt/ 上的工作演示

回答by Gabriel Consalter

CSS class to align a element in middle of the screen:

用于在屏幕中间对齐元素的 CSS 类:

.middle{
    position: absolute;
    top: 50%; /*50% from top*/
    left: 50%; /*50% from left*/ 

    /*remove 50% of element width and height to align the element center in the position*/
    transform: translateY(-50%) translateX(-50%); 
}

Now, add this class to HTML element

现在,将此类添加到 HTML 元素

回答by Rasto

I think it is possible to do it without display: table.

我认为没有display: table.

this is the example:

这是示例:

HTML:

HTML:

<div class="notificationArea">
    something
</div>

CSS:

CSS:

.notificationArea
{
    position: absolute;
    top: 50%;
    bottom: 50%;
    right: 50%;
    left: 50%
}

回答by Tatu Ulmanen

If your main container's height is fluid, your only reliable choice is to use JavaScript ("reliable" is debatable here, of course). In JavaScript, you must first find the height of the container, then the window height and adjust the top offset accordingly. Here's how you'd do it in jQuery:

如果您的主容器的高度是可变的,那么您唯一可靠的选择是使用 JavaScript(当然,“可靠”在这里是有争议的)。在 JavaScript 中,您必须首先找到容器的高度,然后是窗口高度并相应地调整顶部偏移。以下是您在 jQuery 中的做法:

$(function() {
    $(window).resize(function() {
        var top = $(window).height() / 2 - $('#content').height() / 2;
        top = top < 0 ? 0 : top;
        $('#content').css('top', top);
    });
    $(window).resize();
});

And the CSS to make it work:

以及使其工作的 CSS:

#content {
    position: absolute;
    /* Everything else is optional: */
    width: 960px;
    margin: 0 auto;
}

And the HTML:

和 HTML:

...
<body>
    <div id="#content">Content here</div>
</body>
</html>

That's still quite simple, and will work if the user has JavaScript enabled.

这仍然很简单,如果用户启用了 JavaScript,它将起作用。