首页 文章

如何使用CSS轻松地水平居中<div>? [重复]

提问于
浏览
650

这个问题在这里已有答案:

我试图在页面上水平居中 <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

22 回答

  • 3

    margin-left的使用:auto和margin-right:auto在某些情况下可能不起作用 . 这是一个永远有效的解决方案 . 您指定所需的宽度,然后将左边距设置为剩余宽度的一半 .

    <div style="width:80%; margin-left:calc(10%);">
            your_html
        </div>
    
  • 0

    请使用以下代码,您的div将位于中心

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

    }

  • 53

    在这里我添加正确的答案

    您可以使用此代码段并自定义 . 这里我使用2个子块 . 这应该显示页面的中心 . 您可以使用一个或多个块 .

    <html>
    <head>
    <style>
    #parent {
        width: 100%;
        border: solid 1px #aaa;
        text-align: center;
        font-size: 20px;
        letter-spacing: 35px;
        white-space: nowrap;
        line-height: 12px;
        overflow: hidden;
    }
    
    .child {
        width: 100px;
        height: 100px;
        border: solid 1px #ccc;
        display: inline-block;
        vertical-align: middle;
    }
    </style>
    </head>
    
    <body>
    
    <div class="mydiv" id="parent">
    
    
    <div class="child">
    Block 1
    </div>
    <div class="child">
    Block 2
    </div>
    
    </div>
    </body>
    </html>
    
  • 7

    对此问题的最佳回答是使用 margin-auto 但是要使用它,您必须知道 px% 中的 divwidth .

    CSS代码:

    div{
        width:30%;
        margin-left:auto;
        margin-right:auto;
    }
    
  • -3

    我使用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>
    
  • 0

    九年后,我认为是时候推出新版本了 . 这是我的两个(现在是一个)最爱 .

    Margin

    margin 设为 auto . 你应该知道方向序列是 margin: *top* *right* *bottom* *left*;margin: *top&bottom* *left&right*

    aside{
        display: block;
        width: 50px;
        height: 100px;
        background-color: green;
        float: left;
    }
    
    article{
        height: 100px;
        margin: 0 0 0 50px; /* 50px aside width */
        background-color: grey;
    }
    
    div{
      margin: 0 auto;
      display:block;
      width: 60px;
      height: 60px;
      background-color: blue;
      color: white;
    }
    
    <!DOCTYPE html>
    <html>
        <head>
        </head>
        <body>
            <aside>
            </aside>
            <article>           
                    <div>The div</div>
            </article>
        </body>
    </html>
    

    Center: Depricated, don't use this!

    使用 <center></center> 标记作为 <div></div> 的回绕 .

    例:

    aside{
        display:block;
        background-color:green;
        width: 50px;
        height: 100px;
        float: left;
    }
    
    center{
        display:block;
        background-color:grey;
        height: 100px;
        margin-left: 50px; /* Width of the aside */
    }
    
    div{
        display:block; 
        width: 60px; 
        height: 60px; 
        background-color:blue;
        color: white;
    }
    
    <!DOCTYPE html>
    <html>
        <head>
        </head>
        <body>
            <aside>
            </aside>
            <article>
                <center>
                    <div>The div</div>
                </center>
            </article>
        </body>
    </html>
    
  • -4
    margin: 0 auto;
    

    ck has said,并非所有浏览器都支持min-width

  • 2

    如果旧浏览器不是问题,请使用HTML5 / CSS3 . 如果是,请应用polyfills并仍然使用HTML5 / CSS3 . 我假设你的div在这里没有边距或填充,但它们相对容易解释 . 代码如下 .

    .centered {
        position: relative;
        left: 50%;
        transform: translateX(-50%);
    }
    

    这样做是:

    • div 相对于其容器定位;

    • div 的左边界水平放置在 its container width 的50%处;

    • 水平翻译 the div's own width 的50% .

    很容易想象这个过程确认 div 最终会水平居中 . 作为奖励,您可以 center vertically 免费:

    .centered-vertically {
        position: relative;
        top: 50%;
        transform: translateY(-50%);
    }
    

    这种方法的优点是你不必做任何违反直觉的事情,例如考虑你的div文本,将它包装在一个(通常在语义上无用的)附加容器中,或者给它一个固定的宽度,这不是永远可能 .

    如果需要,请不要忘记 transform 的供应商前缀 .

  • 703
    .center {
      height: 20px;
      background-color: blue;
    }
    
    .center>div {
      margin: auto;
      background-color: green;
      width: 200px;
    }
    
    <div class="center">
      <div>You text</div>
    </div>
    

    JsFiddle

  • 2

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

    div.centre {
      width: 200px;
      display: block;
      background-color: #eee;
      margin-left: auto;
      margin-right: auto;
    }
    
    <div class="centre">Some Text</div>
    

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

    div.layout {
      text-align: center;
    }
    
    div.centre {
      text-align: left;
      width: 200px;
      background-color: #eee;
      display: block;
      margin-left: auto;
      margin-right: auto;
    }
    
    <div class="layout">
      <div class="centre">Some Text</div>
    </div>
    
  • 546

    CSSHTML

    div.mydiv {width: 200px; margin: 0 auto}
    
    <div class="mydiv">
        
        I am in the middle
        
    </div>
    

    您的图表也显示了一个块级元素(通常是div),而不是内联元素 .

    在我的头脑中,FF2 / Safari3 / IE7支持 min-width . 可以使用hackety CSS或简单的JS来为IE6做 .

  • 23

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

  • 26

    如果您知道div的宽度并且它已修复,则可以使用以下css:

    margin-left: calc(50% - 'half-of-your-div-width');
    

    'half-of-div-width'应该(显然)是你div的宽度的一半 .

  • 3

    你可以使用这个位置:relative;然后设置左侧和顶部值:

    .cenverDiv{
        position:relative;
        left:30%;
        top:0px;
    }
    
  • 1
    .center {
       margin-left: auto;
       margin-right: auto;
    }
    

    最小宽度不是全局支持的,但可以使用

    .divclass {
       min-width: 200px;
    }
    

    然后你可以设置你的div

    <div class="center divclass">stuff in here</div>
    
  • 34

    如果 <div>position: absolute ,则需要使用 width: 100%;

    #parent {
        width: 100%;
        text-align: center;
    }
    
        #child {
            display: inline-block;
        }
    
  • 24

    您应该在父元素上使用 position: relativetext-align: center ,然后在要居中的子元素上使用 display: inline-block . 这是一个简单的CSS设计模式,可以在所有主流浏览器中使用 . 以下是一个示例或查看CodePen Example .

    p {
      text-align: left;
    }
    .container {
      position: relative;
      display: block;
      text-align: center;
    }
    /* Style your object */
    
    .object {
      padding: 10px;
      color: #ffffff;
      background-color: #556270;
    }
    .centerthis {
      display: inline-block;
    }
    
    <div class="container">
    
      <p>Aeroplanigera Mi Psychopathologia Subdistinctio Chirographum Intuor Sons Superbiloquentia Os Sors Sesquiseptimus Municipatio Archipresbyteratus O Conclusio Compedagogius An Maius Septentrionarius Plas Inproportionabilit Constantinopolis Particularisticus.</p>
    
      <span class="object centerthis">Something Centered</span>
    
      <p>Aeroplanigera Mi Psychopathologia Subdistinctio Chirographum Intuor Sons Superbiloquentia Os Sors Sesquiseptimus Municipatio Archipresbyteratus O Conclusio Compedagogius.</p>
    </div>
    
  • 9

    在您的html文件中,您写道:

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

    你写的css文件:

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

    适合我 .

  • 5

    使用jQuery:

    $(document).ready(function() {
        $(".myElement").wrap( '<span class="myElement_container_new"></span>' ); // for IE6
        $(".myElement_container_new").css({// for IE6
            "display" : "block",
            "position" : "relative",
            "margin" : "0",
            "padding" : "0",
            "border" : "none",
            "background-color" : "transparent",
            "clear" : "both",
            "text-align" : "center"
        });
        $(".myElement").css({
            "display" : "block",
            "position" : "relative",
            "max-width" : "75%", // for example
            "margin-left" : "auto",
            "margin-right" : "auto",
            "clear" : "both",
            "text-align" : "left"
        });
    });
    

    或者,如果你想用类“.myElement”居中每个元素:

    $(document).ready(function() {
        $(".myElement").each(function() {
            $(this).wrap( '<span class="myElement_container_new"></span>' ); // for IE6
            $(".myElement_container_new").css({// for IE6
                "display" : "block",
                "position" : "relative",
                "margin" : "0",
                "padding" : "0",
                "border" : "none",
                "background-color" : "transparent",
                "clear" : "both",
                "text-align" : "center"
            });
            $(this).css({
                "display" : "block",
                "position" : "relative",
                "max-width" : "75%",
                "margin-left" : "auto",
                "margin-right" : "auto",
                "clear" : "both",
                "text-align" : "left"
            });
        });
    });
    
  • 1

    non-fixed width div的情况下(即你不知道div将占用多少空间) .

    #wrapper {
      background-color: green; /* for visualization purposes */
      text-align: center;
    }
    #yourdiv {
      background-color: red; /* for visualization purposes */
      display: inline-block;
    }
    
    <div id="wrapper">    
        <div id="yourdiv">Your text</div>
    </div>
    

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

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

  • 1

    问题的 Headers 和内容实际上是不同的,所以我将使用 Flexbox 发布两个解决方案 .

    我猜 Flexbox 将在IE8和IE9完全被破坏时替换/添加到当前的标准解决方案;)

    检查当前的Browser compatibility table for flexbox

    Single element

    .container {
      display: flex;
      justify-content: center;
    }
    
    <div class="container">
      <img src="http://placehold.it/100x100">
    </div>
    

    Multiple elements but center only one

    默认行为是 flex-direction: row ,它将所有子项对齐在一行中 . 将其设置为 flex-direction: column 将有助于堆叠线 .

    .container {
      display: flex;
      flex-direction: column;
    }
    .centered {
      align-self: center;
    }
    
    <div class="container">
      <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
       </p>
      <div class="centered"><img src="http://placehold.it/100x100"></div>
      <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
        has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. </p>
    </div>
    
  • 1

    将此类添加到您的css文件中它将完美地执行步骤做:

    1)首先创建它

    <div class="center-role-form">
      <!--your div (contrent) place here-->
    </div>
    

    2)将此添加到您的CSS

    .center-role-form {
        width: fit-content;
        text-align: center;
        margin: 1em auto;
    }
    

相关问题