Html 以未知宽度居中 div

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

Centering div with unknown width

htmlcss

提问by Linas

i have div <div id="container"></div>which contains all page content including header footer etc.

我有<div id="container"></div>包含所有页面内容的div ,包括页眉页脚等。

So i would like to center this div to the center of my page, now i have this css:

所以我想将这个 div 居中到我页面的中心,现在我有了这个 css:

#page{
position:relative;
margin:auto;
width:1000px;
}

And it works, but my problem is that content in this div keeps changing so the width changes too, it can be 1000pxor 10100pxso i need something like width:auto;, how can do something like that?

它有效,但我的问题是这个 div 中的内容不断变化,因此宽度也发生变化,它可能是这样的,1000px或者10100px我需要类似的东西width:auto;,如何做这样的事情?

回答by thirtydot

See:http://jsfiddle.net/thirtydot/rjY7F/

见:http : //jsfiddle.net/thirtydot/rjY7F/

HTML:

HTML:

<div id="container">
    i'm as wide as my content
</div>

CSS:

CSS:

body {
    text-align: center;
}
#container {
    text-align: left;
    border: 1px solid red;
    display: inline-block;
    /* for ie6/7: */
    *display: inline;
    zoom: 1;
}

回答by Nate B

One way is to create a wrapper around your #pageelement, let's call it #wrapper:

一种方法是围绕您的#page元素创建一个包装器,我们称之为#wrapper

#wrapper {
   position: relative;
   left: 50%;
   float: left;
}
#page {
   position: relative;
   left: -50%;
   float: left;
}

This will allow the #pagediv to remain a variable width.

这将允许#pagediv 保持可变宽度。

回答by Viruzzo

This will give you a dinamically-sized div that stays at the center of the body and is the smallest size needed to fit the content:

这将为您提供一个尺寸大小的 div,该 div 位于主体的中心,并且是适合内容所需的最小尺寸:

body { text-align: center; }
div.container { display: inline-block; text-align: left; }

回答by PiTheNumber

how about this?

这个怎么样?

body {
  text-align: center;
}
#container {
  text-align: left;
}

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

假设 <body><div id="container"></div></body>