Easy way to center variable width divs in CSS

前端 未结 4 741
清歌不尽
清歌不尽 2020-12-25 12:46

I\'m trying to center a Div that will have varying width\'s (based on content of a website).

I read about a relative positioning technique here:

http://www.t

相关标签:
4条回答
  • 2020-12-25 13:03

    Well, it can't get any simpler than this and has full support on all browsers; doesn't even need a container:

    .centered {
      display:table;
      margin:0 auto;
    }
    
    <div class="centered">
      content
    </div>
    

    Here is a working fiddle: https://jsfiddle.net/1tnprnoz/

    0 讨论(0)
  • 2020-12-25 13:13

    @Talon; you can do it like this http://jsfiddle.net/sandeep/7PXQF/

    CSS:

    .container{
    background-color:red;
        text-align:center;
    }
    .center{
    background-color:yellow;
    display:inline-block;
    text-align:left;}
    

    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>
    
    0 讨论(0)
  • 2020-12-25 13:19

    Now with flex-box you can easily achieve this with justify-content: center;.

    #container{
      background: gray;
      display: flex;
      justify-content: center;
    }
    <div id="container">
      <div id="content" style="width: 200px; padding: 5px; background: #ffa637;">
        This is a centered div This is a centered div This is a centered div This is a centered div
      </div>
    </div>

    This can also be achieved by applying margin: auto to the containers child selector #container>*.

    #container{
      background: #c7c7c7;
    }
    #container>*{
      margin: auto;
    }
    <div id="container">
      <div id="content" style="width: 200px; padding: 5px; background: #ffa637;">
        This is a centered div This is a centered div This is a centered div This is a centered div
      </div>
    </div>

    Note: content div is styled inline as these styles are generated styles and are out of the scope of this question.

    0 讨论(0)
  • 2020-12-25 13:20

    That's a pretty solid method that should work well in most browsers. It's not really that complex when you break it down. Here's a basic example:

    <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>
    
    0 讨论(0)
提交回复
热议问题