在CSS中居中可变宽度div的简便方法

Tal*_*lon 24 css css-float

我试图将一个具有不同宽度的Div(基于网站内容)居中.

我在这里阅读了一个相对定位技术:

http://www.tightcss.com/centering/center_variable_width.htm

但我认为必须有一个更简单的方法吗?

Joe*_*man 34

这是一个非常可靠的方法,应该适用于大多数浏览器.当你把它分解时,它并不是那么复杂.这是一个基本的例子:

<style type="text/css">
#hideoverflow { overflow: hidden; }
#outer { position: relative; left: 50%; float: left; }
#inner { position: relative; left: -50%; float: left; }
</style>

<div id="hideoverflow">
    <div id="outer">
        <div id="inner">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id velit vel  augue fringilla rhoncus at et odio. Suspendisse potenti. Aliquam justo  libero, commodo ut iaculis in, placerat vel purus.
        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 耶稣,你呢?某种忍者?这很棒. (2认同)
  • 今晚我能感觉到它在空中飘扬,哦上帝/我一生都在等待这个答案,哦上帝 (2认同)

san*_*eep 29

@爪; 你可以这样做http://jsfiddle.net/sandeep/7PXQF/

CSS:

.container{
background-color:red;
    text-align:center;
}
.center{
background-color:yellow;
display:inline-block;
text-align:left;}
Run Code Online (Sandbox Code Playgroud)

HTML:

<div class="container">
    <div class="center">
      <p>This is a div with an much wider width, to make the yellow div go off the page to the right.  We'll type a bit more to be sure.</p>
      <p>Most people will see a horizontal scroll bar on the bottom, unless their screen is very wide.</p>
    </div>
  </div>
Run Code Online (Sandbox Code Playgroud)

  • 注意:对于`div`元素,`IE5`` IE6``IE7`不支持`inline-block` (2认同)

sco*_*ord 6

嗯,它再简单不过了,并且完全支持所有浏览器;甚至不需要容器:

.centered {
  display:table;
  margin:0 auto;
}

<div class="centered">
  content
</div>
Run Code Online (Sandbox Code Playgroud)

这是一个工作小提琴: https: //jsfiddle.net/1tnprnoz/