我试图水平中心一个<div>块元素在页面上,并将其设置为最小宽度。最简单的方法是什么?我想要<div>元素内联与我的页面的其余部分。我来举个例子:

page text page text page text page text
page text page text page text page text
               -------
               | div |
               -------
page text page text page text page text
page text page text page text page text

当前回答

你可以在CSS上使用margin: 0 auto而不是margin-left: auto;margin-right:汽车;

其他回答

我使用div和span标签以及css属性,如块,跨浏览器内联块和文本对齐中心,见我的简单示例

<!DOCTYPE html>
<html>
    <head>
       <title>Page Title</title>
       <style>
           .block{display:block;}
           .text-center{text-align:center;}
           .border-dashed-black{border:1px dashed black;}
           .inline-block{
                 display: -moz-inline-stack;
                 display: inline-block;
                 zoom: 1;
                 *display: inline;
            }
           .border-solid-black{border:1px solid black;}
           .text-left{text-align:left;}
        </style>
    </head>
    <body>
          <div class="block text-center border-dashed-black">
              <span class="block text-center">
                  <span class="block"> 
        <!-- The Div we want to center set any width as long as it is not more than the container-->
                      <div class="inline-block text-left border-solid-black" style="width:450px !important;">
                             jjjjjk
                      </div> 
                  </span>
              </span>
          </div>
      </body>
   </html>

在大多数浏览器,这将工作:

div.centre { 宽度:200 px; 显示:块; background - color: # eee; margin-left:汽车; margin-right:汽车; } <div class=" center ">一些文本</div>

在IE6中,你需要添加另一个外部div:

div.layout { text-align:中心; } div.centre { text-align:左; 宽度:200 px; background - color: # eee; 显示:块; margin-left:汽车; margin-right:汽车; } < div class = "布局”> <div class=" center ">一些文本</div> < / div >

在非固定宽度的div的情况下(即你不知道div将占用多少空间)。

#包装{ 背景颜色:绿色;/*用于可视化*/ text-align:中心; } # yourdiv { 背景颜色:红色;/*用于可视化*/ 显示:inline-block; } < div id = "包装" > <div id="yourdiv">你的文本</div> < / div >

请记住,#yourdiv的宽度是动态的->它将增长和缩小以适应其中的文本。

您可以在Caniuse上检查浏览器兼容性

请使用下面的代码,您的div将在中心。

.class-name {
    display:block;
    margin:0 auto;
}

在你的html文件中,你写:

<div class="banner">
  Center content
</div>

你写的CSS文件:

.banner {
display: block;
margin: auto;
width: 100px;
height: 50px;
}

对我有用。