【问题标题】:How do you easily horizontally center a <div> using CSS? [duplicate]如何使用 CSS 轻松地将 <div> 水平居中? [复制]
【发布时间】:2010-10-11 17:05:03
【问题描述】:

我正在尝试将页面上的&lt;div&gt; 块元素水平居中并将其设置为最小宽度。最简单的方法是什么?我希望 &lt;div&gt; 元素与我的页面的其余部分内联。我试着举个例子:

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

【问题讨论】:

  • 我不喜欢这些答案。如果不知道宽度有什么解决办法?例如,它可能只是一个单词。
  • 如果宽度为100%,则需要注意的对齐点将不起作用
  • 我刚刚发现那个 web 生成器:howtocenterincss.com 它的作用是:无论你想居中,但你希望它居中。 ;)
  • 执行以下操作:div.e1{text-align: center;}

标签: css html


【解决方案1】:
.center {
   margin-left: auto;
   margin-right: auto;
}

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

.divclass {
   min-width: 200px;
}

然后你可以将你的 div 设置为

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

【讨论】:

    【解决方案2】:
    margin: 0 auto;
    

    作为ck has saidmin-width并非所有浏览器都支持

    【讨论】:

    • 请注意,这仅在元素还设置了 width 属性时才有效。如果您希望元素的宽度是动态的(基于其内容),请参阅所选答案。
    【解决方案3】:

    CSSHTML

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

    您的图表还显示了块级元素(通常是 div),而不是内联元素。

    在我看来,FF2+/Safari3+/IE7+ 支持min-width。可以为 IE6 使用 Hackty CSS 或一些简单的 JS。

    【讨论】:

    • 感谢您澄清“内联”术语。我想说我不想让它浮在任何文字上。
    【解决方案4】:

    在大多数浏览器中都可以使用:

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

    在 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>

    【讨论】:

    • 是的,由于 IE7 之前的 IE 中的布局错误,您必须这样做。但在 IE8 中,一个简单的 text-align: center 就足够了。 :)
    • 这意味着 IE8 仍然是错误的,因为它不是文本。
    • @Antony Scott:它需要处于严格模式(声明了任何文档类型)。
    • 另外...仅在您知道容器宽度的情况下才有效。如果宽度发生变化,您必须更新您的 CSS(如果内容是动态生成的,这会很糟糕)
    • 我很确定如果您不知道内容的宽度,它会起作用,但是您需要将宽度设置为某个值,因为 div 会扩展到其容器的宽度。
    【解决方案5】:

    非固定宽度 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查看浏览器兼容性

    【讨论】:

    • 我一直在使用“margin:0 auto”解决方案,但这个更好。
    • @UriKlar 因为 margin: 0 auto 更容易且语义更正确。
    • 这解决了margin:0 auto 无法解决的问题。
    • 这个解决方案让 inline-block 很有用!
    • 这种方法的一个缺点是text-align: center是继承的,因此会影响内容,而margin: 0 auto则不会。
    【解决方案6】:

    你可以使用 position:relative;然后设置 left 和 top 值:

    .cenverDiv{
        position:relative;
        left:30%;
        top:0px;
    }
    

    【讨论】:

    • 但这并不容易,需要大量的实验才能获得正确的值。
    • 这没什么用。
    【解决方案7】:

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

    【讨论】:

      【解决方案8】:

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

      JsFiddle

      【讨论】:

      • 这对我有用,特别有助于使整个 div 居中,而不仅仅是其中的文本。
      【解决方案9】:

      使用 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"
              });
          });
      });
      

      【讨论】:

        【解决方案10】:

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

        CSS 代码:

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

        【讨论】:

        • 你可能想写margin: 0 auto;而不是margin-left:auto;margin-right:auto;
        【解决方案11】:

        如果你的&lt;div&gt;position: absolute 你需要使用width: 100%;

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

        【讨论】:

          【解决方案12】:

          我在这里添加正确的答案

          您可以使用此 sn-p 代码并进行自定义。这里我使用了 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>
          

          【讨论】:

            【解决方案13】:

            您应该在父元素上使用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>

            【讨论】:

            • text-align: center 成功了。只需要将它添加到父元素。
            【解决方案14】:

            问题的标题和内容其实不一样,所以我会用Flexbox发布两个解决方案。

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

            查看当前Browser compatibility table for flexbox

            单元素

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

            多个元素但仅居中一个

            默认行为是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>

            【讨论】:

            • 是的,Flexbox 是(并非如此)“现代”的方式:)
            • 是的。是否愿意编辑此内容,使其能够接触到普通观众,蒂维? ;)
            • 当前两个答案没有时,这对我有用。谢谢。
            • @ManojKumar 我认为 flexbox “修复”了很多设计问题,目前几乎所有浏览器都支持。
            • 由于某种原因,margin: 0 auto,在我的 Bourbon Neat 项目中不起作用,但 flexbox 拯救了这一天。
            【解决方案15】:

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

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

            这是做什么的:

            1. 相对于其容器定位div
            2. div的左边界水平放置在其容器宽度的50%处;
            3. 水平向后平移 div 自身宽度的 50%

            很容易想象这个过程来确认div最终会水平居中。作为奖励,您可以垂直居中而无需额外费用:

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

            这种方法的优点是您不必做任何违反直觉的事情,例如将您的 div 视为某种文本,将其包装在一个(通常在语义上无用的)附加容器中,或者给它一个固定的宽度,这并不总是可能的。

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

            【讨论】:

            • 水平方法的一个问题是居中元素不会动态缩放超过父元素宽度的 50%:jsfiddle.net/ywy9w3gk
            【解决方案16】:

            我将 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>
            

            【讨论】:

              【解决方案17】:

              在你写的 html 文件中:

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

              您编写的 css 文件:

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

              为我工作。

              【讨论】:

                【解决方案18】:

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

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

                【讨论】:

                  【解决方案19】:

                  将此类添加到您的 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;
                      display: table;
                  }
                  

                  【讨论】:

                    【解决方案20】:

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

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

                    【讨论】:

                      【解决方案21】:

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

                      保证金

                      margin 设置为auto。你应该知道方向序列是margin: *top* *right* *bottom* *left*;margin: *top&amp;bottom* *left&amp;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>

                      中心:已弃用,请勿使用!

                      使用&lt;center&gt;&lt;/center&gt; 标签作为&lt;div&gt;&lt;/div&gt; 的环绕。

                      例子:

                      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>

                      【讨论】:

                        【解决方案22】:

                        如果你知道你的div的宽度并且它是固定的,你可以使用下面的css:

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

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

                        【讨论】:

                          猜你喜欢
                          • 1970-01-01
                          • 1970-01-01
                          • 2013-08-01
                          • 2023-01-23
                          • 2015-01-12
                          • 2014-04-08
                          • 1970-01-01
                          相关资源
                          最近更新 更多