Javascript 使用CSS跨浏览器div居中对齐

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

Cross browser div center alignment using CSS

javascriptjqueryhtmlcssalignment

提问by Misha Moroshko

What is the easiest way to align a divwhose position is relativehorizontally and vertically using CSS ? The width and the height of the divis unknown, i.e. it should work for every divdimension and in all major browsers. I mean center alignment.

使用 CSS 水平和垂直对齐div位置的最简单方法是relative什么?的宽度和高度div是未知的,即它应该适用于所有div尺寸和所有主要浏览器。我的意思是中心对齐。

I thought to make the horizontal alignment using:

我想使用以下方法进行水平对齐:

margin-left: auto;
margin-right: auto;

like I did here.

就像我在这里所做的那样。

Is this a good cross browser solution for horizontal alignment ?

这是用于水平对齐的良好跨浏览器解决方案吗?

How could I do the vertical alignment ?

我怎么能做垂直对齐?

回答by BalusC

Horizontal centering is only possible if the element's widthis known, else the browser cannot figure where to start and end.

水平居中只有在元素width已知的情况下才有可能,否则浏览器无法确定从哪里开始和结束。

#content {
    width: 300px;
    margin: 0 auto;
}

This is perfectly crossbrowser compatible.

这是完美的跨浏览器兼容。

Vertical centering is only possible if the element is positioned absolutely and has a known height. The absolute positioning would however break margin: 0 auto;so you need to approach this differently. You need to set its topand leftto 50%and the margin-topand margin-leftto the negative halfof its widthand heightrespectively.

仅当元素绝对定位并且具有已知的height. 然而,绝对定位会中断,margin: 0 auto;因此您需要以不同的方式处理它。您需要设置的top,并left50%margin-topmargin-left负半widthheight分别。

Here's a copy'n'paste'n'runnable example:

这是一个复制'n'paste'n'runnable的例子:

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2935404</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>

That said, vertical centering is usually seldom applied in real world.

也就是说,垂直居中在现实世界中通常很少应用。

If the width and height are really unknown beforehand, then you'll need to grab Javascript/jQuery to set the margin-leftand margin-topvalues and live with the fact that client will see the div quickly be shifted during page load, which might cause a "wtf?" experience.

如果事先真的不知道宽度和高度,那么您需要抓取 Javascript/jQuery 来设置margin-leftmargin-top值,并接受这样一个事实,即客户端将在页面加载期间看到 div 快速移动,这可能会导致“wtf? ” 经验。

回答by Misha Reyzlin

"Vertical centering is only possible if the element is positioned absolutely and has a known height." – This statement is not exactly correct.

“只有当元素绝对定位并具有已知高度时,才可能进行垂直居中。” – 这种说法并不完全正确。

You can try and use display:inline-block;and its possibility to be aligned vertically within its parent's box. This technique allows you to align element without knowing its height and width, although it requires you to know parent's height, at the least.

您可以尝试使用display:inline-block;它在其父框内垂直对齐的可能性。这种技术允许您在不知道元素高度和宽度的情况下对齐元素,尽管它至少需要您知道父元素的高度。

If your HTML is this;

如果你的 HTML 是这样的;

<div id="container">
    <div id="aligned-middle" class="inline-block">Middleman</div>
    <div class="strut inline-block">&nbsp;</div>
</div>

And your CSS is:

你的 CSS 是:

#container {
    /* essential for alignment */
    height:300px;
    line-height:300px;
    text-align:center;
    /* decoration */
    background:#eee;
}
    #aligned-middle {
        /* essential for alignment */
        vertical-align:middle;
        /* decoration */
        background:#ccc;
        /* perhaps, reapply inherited values, so your content is styled properly */
        line-height:1.5;
        text-align:left;
    }
    /* this block makes all the "magic", according to http://www.w3.org/TR/CSS2/visudet.html#propdef-vertical-align specification: "The baseline of an 'inline-block' is the baseline of its last line box in the normal flow, unless it has either no in-flow line boxes or if its 'overflow' property has a computed value other than 'visible', in which case the baseline is the bottom margin edge." */
    #container .strut {
        /* parent's height */
        height:300px;
    }
.inline-block {
    display:inline-block;
    *display:inline;/* for IE < 8 */
    *zoom:1;/* for IE < 8 */
}

Then #aligned-middle will be centered within #container. This is the simplest use of this technique, but it's a nice one to be familiar with.

然后#aligned-middle 将在#container 内居中。这是这种技术的最简单的用法,但它是一个很好的熟悉。

Rules marked with "/* for IE < 8 */" should be placed in a separate stylsheet, via use of conditional comments.

标有“/* for IE < 8 */”的规则应通过使用条件注释放置在单独的样式表中。

You can view a working example of this here: http://jsfiddle.net/UXKcA/3/

你可以在这里查看一个工作示例:http: //jsfiddle.net/UXKcA/3/

edit: (this particular snippet tested in ie6 and ff3.6, but I use this a lot, it's pretty cross-browser. if you would need support for ff < 3, you would also need to add display:-moz-inline-stack;under display:inline-block;within .inline-blockrule.)

编辑:(这个特殊的代码片段在IE6和ff3.6测试,但我用这个有很多,它是相当的跨浏览器,如果你需要的FF <3的支持,还需要添加display:-moz-inline-stack;display:inline-block;.inline-block的规则。)

回答by Jay Patel

Check this Demo jsFiddle

检查这个 Demo jsFiddle

Set following twothings

设置以下2件事

  1. HTML alignattribute value center

  2. CSS margin-leftand margin-rightproperties value set auto

  1. HTML对齐属性值中心

  2. CSS margin-leftmargin-right属性值设置为自动

CSS

CSS

<style type="text/css">
     #setcenter{
          margin-left: auto;
          margin-right: auto;    
          // margin: 0px auto; shorthand property
     }
</style>

HTML

HTML

<div align="center" id="setcenter">
   This is some text!
</div>

回答by nickarmstronggr

"If the width and height are really unknown beforehand, then you'll need to grab Javascript/jQuery to set the margin-left and margin-top values and live with the fact that client will see the div quickly be shifted during page load, which might cause a "wtf?" experience."

“如果事先确实不知道宽度和高度,那么您需要抓取 Javascript/jQuery 来设置 margin-left 和 margin-top 值,并接受这样一个事实,即客户端会在页面加载期间看到 div 快速移动,这可能会导致“wtf?”体验。”

You could .hide()the div when the DOM is ready, wait for the page to load, set the div margin-leftand margin-topvalues, and .show()the div again.

您可以.hide()在 DOM 准备好时设置 div,等待页面加载,设置 divmargin-leftmargin-top值,然后.show()再次设置div。

$(function(){
   $("#content").hide();
)};
$(window).bind("load", function() {
   $("#content").getDimSetMargins();
   $("#content").show();
});