Talon
Talon

Reputation: 4995

Easy way to center variable width divs in CSS

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.tightcss.com/centering/center_variable_width.htm

But I thought there has to be an easier way to do it?

Upvotes: 25

Views: 23289

Answers (4)

Munim Munna
Munim Munna

Reputation: 17556

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.

Upvotes: 0

scooterlord
scooterlord

Reputation: 15379

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/

Upvotes: 6

sandeep
sandeep

Reputation: 92863

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

Upvotes: 35

Joe Landsman
Joe Landsman

Reputation: 2177

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>

Upvotes: 36

Related Questions