How to justify divs inside a wrapper div? [duplicate] - html

I want to have 3 divs aligned inside a container div, something like this:
[[LEFT] [CENTER] [RIGHT]]
Container div is 100% wide (no set width), and center div should remain in center after resizing the container.
So I set:
#container{width:100%;}
#left{float:left;width:100px;}
#right{float:right;width:100px;}
#center{margin:0 auto;width:100px;}
But it becomes:
[[LEFT] [CENTER] ]
[RIGHT]
Any tips?

With that CSS, put your divs like so (floats first):
<div id="container">
<div id="left"></div>
<div id="right"></div>
<div id="center"></div>
</div>
P.S. You could also float right, then left, then center. The important thing is that the floats come before the "main" center section.
P.P.S. You often want last inside #container this snippet: <div style="clear:both;"></div> which will extend #container vertically to contain both side floats instead of taking its height only from #center and possibly allowing the sides to protrude out the bottom.

Aligning Three Divs Horizontally Using Flexbox
Here is a CSS3 method for aligning divs horizontally inside another div.
#container {
display: flex; /* establish flex container */
flex-direction: row; /* default value; can be omitted */
flex-wrap: nowrap; /* default value; can be omitted */
justify-content: space-between; /* switched from default (flex-start, see below) */
background-color: lightyellow;
}
#container > div {
width: 100px;
height: 100px;
border: 2px dashed red;
}
<div id="container">
<div></div>
<div></div>
<div></div>
</div>
jsFiddle
The justify-content property takes five values:
flex-start (default)
flex-end
center
space-between
space-around
In all cases, the three divs are on the same line. For a description of each value see: https://stackoverflow.com/a/33856609/3597276
Benefits of flexbox:
minimal code; very efficient
centering, both vertically and horizontally, is simple and easy
equal height columns are simple and easy
multiple options for aligning flex elements
it's responsive
unlike floats and tables, which offer limited layout capacity because they were never intended for building layouts,
flexbox is a modern (CSS3) technique with a broad range of options.
To learn more about flexbox visit:
Methods for Aligning Flex Items
Using CSS flexible boxes ~ MDN
A Complete Guide to Flexbox ~ CSS-Tricks
What the Flexbox?! ~ YouTube video tutorial
Browser support: Flexbox is supported by all major browsers, except IE < 10. Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes. For a quick way to add prefixes use Autoprefixer. More details in this answer.

If you do not want to change your HTML structure you can also do by adding text-align: center; to the wrapper element and a display: inline-block; to the centered element.
#container {
width:100%;
text-align:center;
}
#left {
float:left;
width:100px;
}
#center {
display: inline-block;
margin:0 auto;
width:100px;
}
#right {
float:right;
width:100px;
}
Live Demo: http://jsfiddle.net/CH9K8/

Float property is actually not used to align the text.
This property is used to add element to either right or left or center.
div > div { border: 1px solid black;}
<html>
<div>
<div style="float:left">First</div>
<div style="float:left">Second</div>
<div style="float:left">Third</div>
<div style="float:right">First</div>
<div style="float:right">Second</div>
<div style="float:right">Third</div>
</div>
</html>
for float:left output will be [First][second][Third]
for float:right output will be [Third][Second][First]
That means float => left property will add your next element to left of previous one, Same case with right
Also you have to Consider the width of parent element, if the sum of widths of child elements exceed the width of parent element then the next element will be added at next line
<html>
<div style="width:100%">
<div style="float:left;width:50%">First</div>
<div style="float:left;width:50%">Second</div>
<div style="float:left;width:50%">Third</div>
</div>
</html>
[First] [Second]
[Third]
So you need to Consider All these aspect to get the perfect result

There are several tricks available for aligning the elements.
01. Using Table Trick
.container{
display:table;
}
.left{
background:green;
display:table-cell;
width:33.33vw;
}
.center{
background:gold;
display:table-cell;
width:33.33vw;
}
.right{
background:gray;
display:table-cell;
width:33.33vw;
}
<div class="container">
<div class="left">
Left
</div>
<div class="center">
Center
</div>
<div class="right">
Right
</div>
</div>
02. Using Flex Trick
.container{
display:flex;
justify-content: center;
align-items: center;
}
.left{
background:green;
width:33.33vw;
}
.center{
background:gold;
width:33.33vw;
}
.right{
background:gray;
width:33.33vw;
}
<div class="container">
<div class="left">
Left
</div>
<div class="center">
Center
</div>
<div class="right">
Right
</div>
</div>
03. Using Float Trick
.left{
background:green;
width:100px;
float:left;
}
.center{
background:gold;
width:100px;
float:left;
}
.right{
background:gray;
width:100px;
float:left;
}
<div class="container">
<div class="left">
Left
</div>
<div class="center">
Center
</div>
<div class="right">
Right
</div>
</div>

I like my bars tight and dynamic. This is for CSS 3 & HTML 5
First, setting the Width to 100px is limiting. Don't do it.
Second, setting the container's width to 100% will work ok, until were talking about it being a header/footer bar for the whole app, like a navigation or credits/copyright bar. Use right: 0; instead for that scenario.
You are using id's (hash #container, #left, etc) instead of classes (.container, .left, etc), which is fine, unless you want to repeat your style pattern elsewhere in your code. I'd consider using classes instead.
For HTML, no need to swap order for: left, center, & right. display: inline-block; fixes this, returning your code to something cleaner and logically in order again.
Lastly, you need to clear the floats all up so that it doesn't mess with future <div>. You do this with the clear: both;
To summarize:
HTML:
<div class="container">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
<div class="clear"></div>
</div>
CSS:
.container {right: 0; text-align: center;}
.container .left, .container .center, .container .right { display: inline-block; }
.container .left { float: left; }
.container .center { margin: 0 auto; }
.container .right { float: right; }
.clear { clear: both; }
Bonus point if using HAML and SASS ;)
HAML:
.container
.left
.center
.right
.clear
SASS:
.container {
right: 0;
text-align: center;
.left, .center, .right { display: inline-block; }
.left { float: left; }
.center { margin: 0 auto; }
.right { float: right; }
.clear { clear: both; }
}

This can be easily done using the CSS3 Flexbox, a feature which will be used in the future(When <IE9 is completely dead) by almost every browser.
Check the Browser Compatibility Table
HTML
<div class="container">
<div class="left">
Left
</div>
<div class="center">
Center
</div>
<div class="right">
Right
</div>
</div>
CSS
.container {
display: flex;
flex-flow: row nowrap; /* Align on the same line */
justify-content: space-between; /* Equal margin between the child elements */
}
Output:
.container {
display: flex;
flex-flow: row nowrap; /* Align on the same line */
justify-content: space-between; /* Equal margin between the child elements */
}
/* For Presentation, not needed */
.container > div {
background: #5F85DB;
padding: 5px;
color: #fff;
font-weight: bold;
font-family: Tahoma;
}
<div class="container">
<div class="left">
Left
</div>
<div class="center">
Center
</div>
<div class="right">
Right
</div>
</div>

With twitter bootstrap :
<p class="pull-left">Left aligned text.</p>
<p class="pull-right">Right aligned text.</p>
<p class="text-center">Center aligned text.</p>

possible answer, if you want to keep the order of the html and not use flex.
HTML
<div class="a">
<div class="c">
the
</div>
<div class="c e">
jai ho
</div>
<div class="c d">
watsup
</div>
</div>
CSS
.a {
width: 500px;
margin: 0 auto;
border: 1px solid red;
position: relative;
display: table;
}
.c {
display: table-cell;
width:33%;
}
.d {
text-align: right;
}
.e {
position: absolute;
left: 50%;
display: inline;
width: auto;
transform: translateX(-50%);
}
Code Pen Link

CSS grid can do the job easily:
#container {
display: grid; /* (1) a grid container */
grid-auto-flow:column; /* (2) column layout */
justify-content: space-between; /* (3) align the columns*/
background-color: lightyellow;
}
#container > div {
width: 100px;
height: 100px;
border: 2px dashed red;
}
<div id="container">
<div></div>
<div></div>
<div></div>
</div>

HTML:
<div id="container" class="blog-pager">
<div id="left">Left</div>
<div id="right">Right</div>
<div id="center">Center</div>
</div>
CSS:
#container{width:98%; }
#left{float:left;}
#center{text-align:center;}
#right{float:right;}
text-align:center; gives perfect centre align.
JSFiddle Demo

I did another attempt to simplify this and achieve it without the necessity of a container.
HTML
<div class="box1">left side of the page</div>
<div class="box2">right side of the page</div>
<div class="box3">center of the page </div>
CSS
.box1 {
background-color: #ff0000;
width: 200px;
float: left;
}
.box2 {
background-color: #00ff00;
width: 200px;
float: right;
}
.box3 {
background-color: #0fffff;
width: 200px;
margin: 0 auto;
}
You can see it live at JSFiddle

Using Bootstrap 3 I create 3 divs of equal width (in 12 column layout 4 columns for each div).
This way you can keep your central zone centered even if left/right sections have different widths (if they don't overflow their columns' space).
HTML:
<div id="container">
<div id="left" class="col col-xs-4 text-left">Left</div>
<div id="center" class="col col-xs-4 text-center">Center</div>
<div id="right" class="col col-xs-4 text-right">Right</div>
</div>
CSS:
#container {
border: 1px solid #aaa;
margin: 10px;
padding: 10px;
height: 100px;
}
.col {
border: 1px solid #07f;
padding: 0;
}
CodePen
To create that structure without libraries I copied some rules from Bootstrap CSS.
HTML:
<div id="container">
<div id="left" class="col">Left</div>
<div id="center" class="col">Center</div>
<div id="right" class="col">Right</div>
</div>
CSS:
* {
box-sizing: border-box;
}
#container {
border: 1px solid #aaa;
margin: 10px;
padding: 10px;
height: 100px;
}
.col {
float: left;
width: 33.33333333%;
border: 1px solid #07f;
padding: 0;
}
#left {
text-align: left;
}
#center {
text-align: center;
}
#right {
text-align: right;
}
CopePen

If the left, center, and right DIVs have different widths, you can accomplish this as follows:
#container {
position: relative;
width: 100%;
text-align: center;
}
#left {
position: absolute;
left: 0px;
}
#right {
position: absolute;
right: 0px;
}
#center {
display: inline-block;
}
If your center DIV is text, you don't need the #center CSS.

Here are the changes that I had to make to the accepted answer when I did this with an image as the centre element:
Make sure the image is enclosed within a div (#center in this case). If it isn't, you'll have to set display to block, and it seems to centre relative to the space between the floated elements.
Make sure to set the size of both the image and its container:
#center {
margin: 0 auto;
}
#center, #center > img {
width: 100px;
height: auto;
}

You can try this:
Your html code like this:
<div id="container">
<div id="left"></div>
<div id="right"></div>
<div id="center"></div>
</div>
and your css code like this:
#container{width:100%;}
#left{float:left;width:100px;}
#right{float:right;width:100px;}
#center{margin:0 auto;width:100px;}
so, it's output should be get like this:
[[LEFT] [CENTER] [RIGHT]]

Use CSS Grid
layout {
display: grid;
grid-template-columns: repeat(3,1fr);
}
start-column {
justify-self: start;
}
center-column {
justify-self: center;
}
end-column {
justify-self: end;
}
<layout>
<start-column>
<button>Start</button>
</start-column>
<center-column>
<p>Center Donec non urna ipsum. Nullam euismod, lacus ac malesuada varius, mauris erat ullamcorper erat, eget dignissim tortor felis et sapien. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi faucibus turpis et augue dapibus bibendum.</p>
</center-column>
<end-column>
End
</end-column>
</layout>

.processList
text-align: center
li
.leftProcess
float: left
.centerProcess
float: none
display: inline-block
.rightProcess
float: right
html
ul.processList.clearfix
li.leftProcess
li.centerProcess
li.rightProcess

You've done it correctly, you only need to clear your floats.
Simply add
overflow: auto;
to your container class.

The easiest solution is to crate a table with 3 columns and center that table.
html:
<div id="cont">
<table class="aa">
<tr>
<td>
<div id="left">
<h3 class="hh">Content1</h3>
</div>
</td>
<td>
<div id="center">
<h3 class="hh">Content2</h3>
</div>
</td>
<td>
<div id="right"><h3 class="hh">Content3</h3>
</div>
</td>
</tr>
</table>
</div>
css:
#cont
{
margin: 0px auto;
padding: 10px 10px;
}
#left
{
width: 200px;
height: 160px;
border: 5px solid #fff;
}
#center
{
width: 200px;
height: 160px;
border: 5px solid #fff;
}
#right
{
width: 200px;
height: 160px;
border: 5px solid #fff;
}

#warpcontainer {width:800px; height:auto; border: 1px solid #000; float:left; }
#warpcontainer2 {width:260px; height:auto; border: 1px solid #000; float:left; clear:both; margin-top:10px }

Related

Floating child div to fill only remaining space

I want that yellow box to fill all the available space both vertically and horizontally without overlaying the picture.
(I'm trying to do it without using table properties)
Any ideas?
This is how it looks now:
and this is what i want:
.content-block-body{
width: 100%;
background-color: brown;
overflow:auto;
}
.content-block-text{
float:left;
background-color: red;
padding:2%;
}
.content-block-image{
background-color: greenyellow;
float: right;
}
<div class="content-block-body">
<div class="content-block-text">
<div>月額固定と成果報酬が選べます</div>
<div>成果報酬額に上限おもうけられます</div>
<div>料金が明瞭で予算に合わせた対策が可能</div>
</div>
<div class="content-block-image"> <img src="image-1.jpg"> </div>
</div>
The problem is the float: left makes the yellow area not "stretch." To make the image float to the right of the text, it has to come before the text. So we change the order of the content blocks:
<div class="content-block-body">
<div class="content-block-image"> <img src="image-1.jpg"> </div>
<div class="content-block-text">
<div>月額固定と成果報酬が選べます</div>
<div>成果報酬額に上限おもうけられます</div>
<div>料金が明瞭で予算に合わせた対策が可能</div>
</div>
</div>
And then adjust the css:
.content-block-body {
width: 100%;
background-color: brown;
overflow:auto;
}
.content-block-text{
/*float:left;*/ /* this we remove */
background-color: red;
padding:2%;
/* this we add: */
overflow: auto;
}
.content-block-image{
background-color: greenyellow;
float: right;
}
Note that whenever you float things you'll most likely need to add what's called a "clearfix". In this case, apply the clearfix to the .content-block-body to make it extend vertically to fit the floated element http://nicolasgallagher.com/micro-clearfix-hack/
You have to specify width of left block and right block in CSS and make image width 100%
.content-block-body{
width: 100%;
background-color: brown;
overflow:auto;
}
.content-block-text{
float:left;
background-color: yellow;
padding:2%;
width:56%;
}
.content-block-image{
background-color: greenyellow;
float: right;
min-width:200px;
width:40%;
}
.content-block-image img{
width:100%;
}
<div class="content-block-body">
<div class="content-block-text">
<div>月額固定と成果報酬が選べます</div>
<div>成果報酬額に上限おもうけられます</div>
<div>料金が明瞭で予算に合わせた対策が可能</div>
</div>
<div class="content-block-image"> <img src="image-1.jpg"> </div>
</div>
You can use css3 flex. That's the only thing that works just fine when it comes to getting the height of the parent node for child node. All the hacks for old browsers doesn't work always.
.content-block-body{
width: 100%;
background-color: brown;
overflow:auto;
display: flex;
clear: both;
}
.content-block-text{
float:left;
background-color: red;
align-items: stretch;
}
.content-block-image{
flex: 1;
background-color: greenyellow;
}
.content-block-image img{
float: right;
}
<div class="content-block-body">
<div class="content-block-text">
<div>月額固定と成果報酬が選べます</div>
<div>成果報酬額に上限おもうけられます</div>
<div>料金が明瞭で予算に合わせた対策が可能</div>
</div>
<div class="content-block-image">
<img src="//placehold.it/250x250">
</div>
</div>
also check out this cool site for code snippets on centering in css.

HTML CSS Horizontally stacked elements 1 fills remaining width

Update: This is the closest to a solution so far: http://jsfiddle.net/bfcr62yd/11/
I am having trouble solving the following problem. In short, I need one element to fill the remaining width, where all other elements that are all stacked horizontally have fixed widths.
The UI has 5 wrapper elements that need to be stacked horizontally with a fixed min-width. The 2 elements on the left and the 2 elements on the right have fixed widths. The center wrapper element width needs to dynamically fill the remaining width. The center element has a child element that has a very large fixed width. If the responsive parent width is smaller than the child fixed width, I would like the child to overflow-x: scroll (hide the remaining width and view it via scroll).
<div>
<div class="box dates"></div>
<div class="box dates_presets"></div>
<div class="box groupings"></div> <!-- to fill remaining width -->
<div class="box columns"></div>
<div class="box columns_video"></div>
</div>
My attempts so far:
http://jsfiddle.net/bwgrwgnz/1/
http://jsfiddle.net/hycd4non/13/
I have found this simple example that works with only 2 elements: http://jsfiddle.net/SpSjL/
Try using display: table | table-row | table-cell:
.table { display: table; width: 100%; } /* set the width to your maximum width value */
.tr { display: table-row; }
.tr div { display: table-cell; }
you also need to remove all of the floats from your 'table-cell' elements
JSFiddle Demo
And, one more no-flexbox solution. Problem was to force scrolling. One more or less dirty hack made it!
http://jsfiddle.net/d4n2fnpy/1/
#table {
display:table;
width:100%;
table-layout:fixed;
}
.box {
border: 2px dashed #00f;
min-height: 100px;
padding-right: 10px;
display:table-cell;
word-wrap:break-word;
}
.dates {
width: 200px;
}
.dates_presets {
width:200px;
}
.groupings {
overflow-x: scroll;
word-wrap:initial!important;
display:block!important;
width:auto;
}
.columns {
width:200px;
}
.columns_video {
width: 200px;
}
P.S. Set overflow-x: auto; to remove ugly scroler when there is no need for it...
Are you looking for something like this? http://jsfiddle.net/DIRTY_SMITH/bfcr62yd/14/
I restructured it but I think this is what you wanted
HTML
<div id="container">
<div class="box-1"></div>
<div class="box-2"></div>
<div class="box-3">
<div class="inside-div">
blah blah blah blah blah blah blah blah blah blah blah blah
</div>
</div>
<div class="box-4"></div>
<div class="box-5"></div>
</div>
CSS
#container{width: 100%;}
.box-1, .box-2, .box-4, .box-5{width: 200px; height: 100px; background-color: blue; float: left;}
.box-3{width: calc(100% - 800px); height: 100px; overflow-x: scroll; overflow-y: hidden;background-color: red; float: left;}
.inside-div{height: 50px; width: 400px;}
.mini-box {
padding: 5px;
margin: 5px;
border: 1px solid red;
width: 20px;
}
I added a width using Calc(). It's pretty straight forward. I have it here: http://jsfiddle.net/bwgrwgnz/3/
width: calc(100% - 770px);
But to be honest, flexbox is probably the way you want to go if you can deal with the lack of support in older browsers.
Ps. calc() isn't supported everywhere either.
Edit: There is a table example above as well which could work well.
My solution using tables: http://jsfiddle.net/bwgrwgnz/41/
.box {
border: 2px dashed #00f;
height: 100px;
width: 50px;
}
.dynamic-box {
width:auto !important;
}
.dynamic-box-fixed-inner {
display:block !important;
overflow-x:scroll;
}
.inner-item {
position:inline-block;
padding:5px;
}
.table { display: table; width: 100%; table-layout:fixed; }
.tr { display: table-row; }
.tr div { display: table-cell; }
<div class="table">
<div class="tr">
<div class="box">a</div>
<div class="box">b</div>
<!-- this element should fill the remaining width -->
<div class="box dynamic-box">
<div class="dynamic-box-fixed-inner">
<div class="inner-item">item</div>
<div class="inner-item">item</div>
...
</div>
</div>
<div class="box">d</div>
</div>
</div>

Create div with two divs inside that need to stay centered

I'm making a web site responsive, and on the home page I should insert two "containers" that should be centered and aligned. (containers in this case are two divs with inside images and text)
I wish they would behave in this way
and when the page is "restricted", the two divs should position itself in this way
I tried like this, but it is not exactly what I would get
<div style="">
<div style="width: 300px;float: left;">
div 1
</div>
<div style="width: 300px;float: left;">
div 2
</div>
</div>
I'd try to use display: inline-block property. In this way you don't have to apply 'overflow' for parent and it's pretty easy to make blocks centered.
HTML:
<div class="wrapper">
<div class="box">Div 1</div>
<div class="box">Div 2</div>
</div>
CSS:
.wrapper {
text-align: center;
/* Just decoration */
border: 1px solid blue;
padding: 20px;
}
.wrapper .box {
display: inline-block;
width: 300px;
height: 50px;
/* Just decoration */
border: 1px solid green;
}
Take a look at the fiddle http://jsfiddle.net/caprella/y4BQ3/
I put something quick together for you. You will have to use media queries to find the size of the page when you want the style to switch. Mess around with my example and you should be able to figure something out to your liking.
<div id="box">
<div class="innerBox">
div 1
</div>
<div class="innerBox">
div 2
</div>
<div class="clear"></div>
</div>
And the CSS...
#box {
width:88%;
background:red;
padding:20px 6%;
}
.clear{clear:both}
.innerBox {
width:41%;
float:left;
background:blue;
display:block;
}
.innerBox:first-child {
margin-right:18%;
}
#media screen and (max-width: 400px) {
#box .innerBox {
float:none;
width:100%;
margin:20px 0 0 0;
}
#box .innerBox:first-child {
margin-top:0;
}
}
}
JsFIddle link: http://jsfiddle.net/x3JLX/
Check out this Fiddle. There's only a few simple changes to your existing code, which I included below.
http://jsfiddle.net/ArKKG/
<div style="overflow:auto; height: 100% text-align: center;">
<div style="width: 300px; height: 50px;float: left;">
div 1
</div>
<div style="width: 300px;height: 50px;float: left;">
div 2
</div>
</div>
And some CSS to make them visible, and keep the borders separated.
div{
border: 1px solid black;
margin: 4px;
}

Centering floating divs within another div

I've searched other questions and, while this problem seems similar to a couple of others, nothing I've seen so far seems to address the issue that I'm having.
I have a div which contains a number of other divs, each of which is floated left. These divs each contain a photo and a caption. All I want is for the group of photos to be centered within the containing div.
As you can see from the code below, I've tried using both overflow:hidden and margin:x auto on the parent divs, and I've also added a clear:both (as suggested in another topic) after the photos. Nothing seems to make a difference.
Thank you. I appreciate any suggestions.
<div style="position: relative; margin: 0 auto; overflow: hidden; text-align: center;">
<h4>Section Header</h4>
<div style="margin: 2em auto;">
<div style="float: left; margin: auto 1.5em;">
<img src="photo1.jpg" /><br />
Photo Caption
</div>
<div style="float: left; margin: auto 1.5em;">
<img src="photo2.jpg" /><br />
Photo Caption
</div>
<div style="float: left; margin: auto 1.5em;">
<img src="photo3.jpg" /><br />
Photo Caption
</div>
<div style="clear: both; height: 0; overflow: hidden;"> </div>
</div>
</div>
First, remove the float attribute on the inner divs. Then, put text-align: center on the main outer div. And for the inner divs,
use display: inline-block. Might also be wise to give them explicit widths too.
<div style="margin: auto 1.5em; display: inline-block;">
<img title="Nadia Bjorlin" alt="Nadia Bjorlin" src="headshot.nadia.png"/>
<br/>
Nadia Bjorlin
</div>
With Flexbox you can easily horizontally (and vertically) center floated children inside a div.
So if you have simple markup like so:
<div class="wpr">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
with CSS:
.wpr
{
width: 400px;
height: 100px;
background: pink;
padding: 10px 30px;
}
.wpr span
{
width: 50px;
height: 50px;
background: green;
float: left; /* **children floated left** */
margin: 0 5px;
}
(This is the (expected - and undesirable) RESULT)
Now add the following rules to the wrapper:
display: flex;
justify-content: center; /* align horizontal */
and the floated children get aligned center (DEMO)
Just for fun, to get vertical alignment as well just add:
align-items: center; /* align vertical */
DEMO
I accomplished the above using relative positioning and floating to the right.
HTML code:
<div class="clearfix">
<div class="outer-div">
<div class="inner-div">
<div class="floating-div">Float 1</div>
<div class="floating-div">Float 2</div>
<div class="floating-div">Float 3</div>
</div>
</div>
</div>
CSS:
.outer-div { position: relative; float: right; right: 50%; }
.inner-div { position: relative; float: right; right: -50%; }
.floating-div { float: left; border: 1px solid red; margin: 0 1.5em; }
.clearfix:before,
.clearfix:after { content: " "; display: table; }
.clearfix:after { clear: both; }
.clearfix { *zoom: 1; }
JSFiddle: http://jsfiddle.net/MJ9yp/
This will work in IE8 and up, but not earlier (surprise, surprise!)
I do not recall the source of this method unfortunately, so I cannot give credit to the original author. If anybody else knows, please post the link!
The following solution does not use inline blocks. However, it requires two helper divs:
The content is floated
The inner helper is floated (it stretches as much as the content)
The inner helper is pushed right 50% (its left aligns with center of outer helper)
The content is pulled left 50% (its center aligns with left of inner helper)
The outer helper is set to hide the overflow
.ca-outer {
overflow: hidden;
background: #FFC;
}
.ca-inner {
float: left;
position: relative;
left: 50%;
background: #FDD;
}
.content {
float: left;
position: relative;
left: -50%;
background: #080;
}
/* examples */
div.content > div {
float: left;
margin: 10px;
width: 100px;
height: 100px;
background: #FFF;
}
ul.content {
padding: 0;
list-style-type: none;
}
ul.content > li {
margin: 10px;
background: #FFF;
}
<div class="ca-outer">
<div class="ca-inner">
<div class="content">
<div>Box 1</div>
<div>Box 2</div>
<div>Box 3</div>
</div>
</div>
</div>
<hr>
<div class="ca-outer">
<div class="ca-inner">
<ul class="content">
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
<li>Nullam efficitur nulla in libero consectetur dictum ac a sem.</li>
<li>Suspendisse iaculis risus ut dapibus cursus.</li>
</ul>
</div>
</div>
display: inline-block; won't work in any of IE browsers. Here is what I used.
// change the width of #boxContainer to
// 1-2 pixels higher than total width of the boxes inside:
#boxContainer {
width: 800px;
height: auto;
text-align: center;
margin-left: auto;
margin-right: auto;
}
#Box{
width: 240px;
height: 90px;
background-color: #FFF;
float: left;
margin-left: 10px;
margin-right: 10px;
}
Solution:
<!DOCTYPE HTML>
<html>
<head>
<title>Knowledge is Power</title>
<script src="js/jquery.js"></script>
<script type="text/javascript">
</script>
<style type="text/css">
#outer {
text-align:center;
width:100%;
height:200px;
background:red;
}
#inner {
display:inline-block;
height:200px;
background:yellow;
}
</style>
</head>
<body>
<div id="outer">
<div id="inner">Hello, I am Touhid Rahman. The man in Light</div>
</div>
</body>
</html>
In my case, I could not get the answer by #Sampson to work for me, at best I got a single column centered on the page. In the process however, I learned how the float actually works and created this solution. At it's core the fix is very simple but hard to find as evident by this thread which has had more than 146k views at the time of this post without mention.
All that is needed is to total the amount of screen space width that the desired layout will occupy then make the parent the same width and apply margin:auto. That's it!
The elements in the layout will dictate the width and height of the "outer" div. Take each "myFloat" or element's width or height + its borders + its margins and its paddings and add them all together. Then add the other elements together in the same fashion. This will give you the parent width. They can all be somewhat different sizes and you can do this with fewer or more elements.
Ex.(each element has 2 sides so border, margin and padding get multiplied x2)
So an element that has a width of 10px, border 2px, margin 6px, padding 3px would look like this:
10 + 4 + 12 + 6 = 32
Then add all of your element's totaled widths together.
Element 1 = 32
Element 2 = 24
Element 3 = 32
Element 4 = 24
In this example the width for the "outer" div would be 112.
.outer {
/* floats + margins + borders = 270 */
max-width: 270px;
margin: auto;
height: 80px;
border: 1px;
border-style: solid;
}
.myFloat {
/* 3 floats x 50px = 150px */
width: 50px;
/* 6 margins x 10px = 60 */
margin: 10px;
/* 6 borders x 10px = 60 */
border: 10px solid #6B6B6B;
float: left;
text-align: center;
height: 40px;
}
<div class="outer">
<div class="myFloat">Float 1</div>
<div class="myFloat">Float 2</div>
<div class="myFloat">Float 3</div>
</div>

Centering a div block without the width

I have a problem when I try to center the div block "products" because I don't know in advance the div width. Anybody have a solution?
Update: The problem I have is I don't know how many products I'll display, I can have 1, 2 or 3 products, I can center them if it was a fixed number as I'd know the width of the parent div, I just don't know how to do it when the content is dynamic.
.product_container {
text-align: center;
height: 150px;
}
.products {
height: 140px;
text-align: center;
margin: 0 auto;
clear: ccc both;
}
.price {
margin: 6px 2px;
width: 137px;
color: #666;
font-size: 14pt;
font-style: normal;
border: 1px solid #CCC;
background-color: #EFEFEF;
}
<div class="product_container">
<div class="products" id="products">
<div id="product_15">
<img src="/images/ecommerce/card_default.png">
<div class="price">R$ 0,01</div>
</div>
<div id="product_15">
<img src="/images/ecommerce/card_default.png">
<div class="price">R$ 0,01</div>
</div>
<div id="product_15">
<img src="/images/ecommerce/card_default.png">
<div class="price">R$ 0,01</div>
</div>
</div>
</div>
Update 27 Feb 2015: My original answer keeps getting voted up, but now I normally use #bobince's approach instead.
.child { /* This is the item to center... */
display: inline-block;
}
.parent { /* ...and this is its parent container. */
text-align: center;
}
My original post for historical purposes:
You might want to try this approach.
<div class="product_container">
<div class="outer-center">
<div class="product inner-center">
</div>
</div>
<div class="clear"/>
</div>
Here's the matching style:
.outer-center {
float: right;
right: 50%;
position: relative;
}
.inner-center {
float: right;
right: -50%;
position: relative;
}
.clear {
clear: both;
}
JSFiddle
The idea here is that you contain the content you want to center in two divs, an outer one and an inner one. You float both divs so that their widths automatically shrink to fit your content. Next, you relatively position the outer div with it's right edge in the center of the container. Lastly, you relatively position the inner div the opposite direction by half of its own width (actually the outer div's width, but they are the same). Ultimately that centers the content in whatever container it's in.
You may need that empty div at the end if you depend on your "product" content to size the height for the "product_container".
An element with ‘display: block’ (as div is by default) has a width determined by the width of its container. You can't make a block's width dependent on the width of its contents (shrink-to-fit).
(Except for blocks that are ‘float: left/right’ in CSS 2.1, but that's no use for centering.)
You could set the ‘display’ property to ‘inline-block’ to turn a block into a shrink-to-fit object that can be controlled by its parent's text-align property, but browser support is spotty. You can mostly get away with it by using hacks (eg. see -moz-inline-stack) if you want to go that way.
The other way to go is tables. This can be necessary when you have columns whose width really can't be known in advance. I can't really tell what you're trying to do from the example code — there's nothing obvious in there that would need a shrink-to-fit block — but a list of products could possibly be considered tabular.
[PS. never use ‘pt’ for font sizes on the web. ‘px’ is more reliable if you really need fixed size text, otherwise relative units like ‘%’ are better. And “clear: ccc both” — a typo?]
.center{
text-align:center;
}
.center > div{ /* N.B. child combinators don't work in IE6 or less */
display:inline-block;
}
JSFiddle
Most browsers support the display: table; CSS rule. This is a good trick to center a div in a container without adding extra HTML nor applying constraining styles to the container (like text-align: center; which would center all other inline content in the container), while keeping dynamic width for the contained div:
HTML:
<div class="container">
<div class="centered">This content is centered</div>
</div>
CSS:
.centered { display: table; margin: 0 auto; }
.container {
background-color: green;
}
.centered {
display: table;
margin: 0 auto;
background-color: red;
}
<div class="container">
<div class="centered">This content is centered</div>
</div>
Update (2015-03-09):
The proper way to do this today is actually to use flexbox rules. Browser support is a little bit more restricted (CSS table support vs flexbox support) but this method also allows many other things, and is a dedicated CSS rule for this type of behavior:
HTML:
<div class="container">
<div class="centered">This content is centered</div>
</div>
CSS:
.container {
display: flex;
flex-direction: column; /* put this if you want to stack elements vertically */
}
.centered { margin: 0 auto; }
.container {
display: flex;
flex-direction: column; /* put this if you want to stack elements vertically */
background-color: green;
}
.centered {
margin: 0 auto;
background-color: red;
}
<div class="container">
<div class="centered">This content is centered</div>
</div>
six ways to skin that cat:
Button one: anything of type display: block will assume the full parents width. (unless combined with float or a display: flex parent). True. Bad example.
Button 2: going for display: inline-block will lead to automatic (rather than full) width. You can then center using text-align: center on the wrapping block. Probably the easiest, and most widely compatible, even with ‘vintage’ browsers...
.wrapTwo
text-align: center;
.two
display: inline-block; // instantly shrinks width
Button 3:
No need to put anything on the wrap. So perhaps this is the most elegant solution. Also works vertically. (Browser support for transtlate is good enough (≥IE9) these days...).
position: relative;
display: inline-block; // instantly shrinks width
left: 50%;
transform: translateX(-50%);
Btw: Also a great way for vertically centering blocks of unknown height (in connection with absolute positioning).
Button 4:
Absolute positioning. Just make sure to reserve enough height in the wrapper, since noone else will (neither clearfix nor implicit...)
.four
position absolute
top 0
left 50%
transform translateX(-50%)
.wrapFour
position relative // otherwise, absolute positioning will be relative to page!
height 50px // ensure height
background lightgreen // just a marker
Button 5:
float (which brings also block-level elements to dynamic width) and a relative shift. Although I've never seen this in the wild. Perhaps there are disadvantages...
.wrapFive
&:after // aka 'clearfix'
content ''
display table
clear both
.five
float left
position relative
left 50%
transform translateX(-50%)
Update: Button 6:
And nowadays, you could also use flex-box. Note, that styles apply to the wrapper of the centered object.
.wrapSix
display: flex
justify-content: center
→ full source code (stylus syntax)
I found a more elegant solution, combining "inline-block" to avoid using float and the hacky clear:both. It still requires nested divs tho, which isnt very semantic but it just works...
div.outer{
display:inline-block;
position:relative;
left:50%;
}
div.inner{
position:relative;
left:-50%;
}
Hope it helps!
<div class="outer">
<div class="target">
<div class="filler">
</div>
</div>
</div>
.outer{
width:100%;
height: 100px;
}
.target{
position: absolute;
width: auto;
height: 100px;
left: 50%;
transform: translateX(-50%);
}
.filler{
position:relative;
width:150px;
height:20px;
}
If the target element is absolutely positioned, you can center it by moving it 50% in one direction (left: 50%) and then transforming it 50% in the opposition direction (transform:translateX(-50%)). This works without defining the target element's width (or with width:auto). The parent element's position can be static, absolute, relative, or fixed.
By default, div elements are displayed as block elements, so they have 100% width, making centering them meaningless. As suggested by Arief, you must specify a width and you can then use auto when specifying margin in order to center a div.
Alternatively, you could also force display: inline, but then you'd have something that pretty much behaves like a span instead of a div, so that doesn't make a lot of sense.
This will center an element such as an Ordered List, or Unordered List, or any element.
Just wrap it with a Div with the class of outerElement and give the inner element the class of innerElement.
The outerelement class accounts for IE, old Mozilla, and most newer browsers.
.outerElement {
display: -moz-inline-stack;
display: inline-block;
vertical-align: middle;
zoom: 1;
position: relative;
left: 50%;
}
.innerElement {
position: relative;
left: -50%;
}
use css3 flexbox with justify-content:center;
<div class="row">
<div class="col" style="background:red;">content1</div>
<div class="col" style="">content2</div>
</div>
.row {
display: flex; /* equal height of the children */
height:100px;
border:1px solid red;
width: 400px;
justify-content:center;
}
Slight variation on Mike M. Lin's answer
If you add overflow: auto; ( or hidden ) to div.product_container, then you don't need div.clear.
This is derived from this article -> http://www.quirksmode.org/css/clearing.html
Here is modified HTML:
<div class="product_container">
<div class="outer-center">
<div class="product inner-center">
</div>
</div>
</div>
And here is modified CSS:
.product_container {
overflow: auto;
/* width property only required if you want to support IE6 */
width: 100%;
}
.outer-center {
float: right;
right: 50%;
position: relative;
}
.inner-center {
float: right;
right: -50%;
position: relative;
}
The reason, why it's better without div.clear (apart that it feels wrong to have an empty element) is Firefox'es overzealous margin assignment.
If, for example, you have this html:
<div class="product_container">
<div class="outer-center">
<div class="product inner-center">
</div>
</div>
<div style="clear: both;"></div>
</div>
<p style="margin-top: 11px;">Some text</p>
then, in Firefox (8.0 at the point of writing), you will see 11px margin before product_container. What's worse, is that you will get a vertical scroll bar for the whole page, even if the content fits nicely into the screen dimensions.
Try this new css and markup
Here is modified HTML:
<div class="product_container">
<div class="products" id="products">
<div id="product_15" class="products_box">
<img src="/images/ecommerce/card_default.png">
<div class="price">R$ 0,01</div>
</div>
<div id="product_15" class="products_box">
<img src="/images/ecommerce/card_default.png">
<div class="price">R$ 0,01</div>
</div>
<div id="product_15" class="products_box">
<img src="/images/ecommerce/card_default.png">
<div class="price">R$ 0,01</div>
</div>
</div>
And here is modified CSS:
<pre>
.product_container
{
text-align: center;
height: 150px;
}
.products {
left: 50%;
height:35px;
float:left;
position: relative;
margin: 0 auto;
width:auto;
}
.products .products_box
{
width:auto;
height:auto;
float:left;
right: 50%;
position: relative;
}
.price {
margin: 6px 2px;
width: 137px;
color: #666;
font-size: 14pt;
font-style: normal;
border: 1px solid #CCC;
background-color: #EFEFEF;
}
<div class="product_container">
<div class="outer-center">
<div class="product inner-center">
</div>
</div>
<div class="clear"></div>
</div>
.outer-center
{
float: right;
right: 50%;
position: relative;
}
.inner-center
{
float: right;
right: -50%;
position: relative;
}
.clear
{
clear: both;
}
.product_container
{
overflow:hidden;
}
If you dont provide "overflow:hidden" for ".product_container" the "outer-center" div will overlap other nearby contents to the right of it. Any links or buttons to the right of "outer-center" wont work. Try background color for "outer-center" to understand the need of "overflow :hidden"
I found interesting solution, I was making slider and had to center slide controls and I did this and works fine. You can also add relative position to parent and move child position vertical. Take a look http://jsfiddle.net/bergb/6DvJz/
CSS:
#parent{
width:600px;
height:400px;
background:#ffcc00;
text-align:center;
}
#child{
display:inline-block;
margin:0 auto;
background:#fff;
}
HTML:
<div id="parent">
<div id="child">voila</div>
</div>
Do display:table; and set margin to auto
Important bit of code:
.relatedProducts {
display: table;
margin-left: auto;
margin-right: auto;
}
No matter how many elements you got now it will auto align in center
Example in code snippet:
.relatedProducts {
display: table;
margin-left: auto;
margin-right: auto;
}
a {
text-decoration:none;
}
<div class="row relatedProducts">
<div class="homeContentTitle" style="margin: 100px auto 35px; width: 250px">Similar Products</div>
test1
test2
test3
</div>
I'm afraid the only way to do this without explicitly specifying the width is to use (gasp) tables.
Crappy fix, but it does work...
CSS:
#mainContent {
position:absolute;
width:600px;
background:#FFFF99;
}
#sidebar {
float:left;
margin-left:610px;
max-width:300;
background:#FFCCCC;
}
#sidebar{
text-align:center;
}
HTML:
<center>
<table border="0" cellspacing="0">
<tr>
<td>
<div id="mainContent">
1<br/>
<br/>
123<br/>
123<br/>
123<br/>
</div><div id="sidebar"><br/>
</div></td>
</tr>
</table>
</center>
Simple fix that works in old browsers (but does use tables, and requires a height to be set):
<div style="width:100%;height:40px;position:absolute;top:50%;margin-top:-20px;">
<table style="width:100%"><tr><td align="center">
In the middle
</td></tr></table>
</div>
<style type="text/css">
.container_box{
text-align:center
}
.content{
padding:10px;
background:#ff0000;
color:#ffffff;
}
use span istead of the inner divs
<div class="container_box">
<span class="content">Hello</span>
</div>
I know this question is old, but I'm taking a crack at it. Very similar to bobince's answer but with working code example.
Make each product an inline-block. Center the contents of the container. Done.
http://jsfiddle.net/rgbk/6Z2Re/
<style>
.products{
text-align:center;
}
.product{
display:inline-block;
text-align:left;
background-image: url('http://www.color.co.uk/wp-content/uploads/2013/11/New_Product.jpg');
background-size:25px;
padding-left:25px;
background-position:0 50%;
background-repeat:no-repeat;
}
.price {
margin: 6px 2px;
width: 137px;
color: #666;
font-size: 14pt;
font-style: normal;
border: 1px solid #CCC;
background-color: #EFEFEF;
}
</style>
<div class="products">
<div class="product">
<div class="price">R$ 0,01</div>
</div>
<div class="product">
<div class="price">R$ 0,01</div>
</div>
<div class="product">
<div class="price">R$ 0,01</div>
</div>
<div class="product">
<div class="price">R$ 0,01</div>
</div>
<div class="product">
<div class="price">R$ 0,01</div>
</div>
<div class="product">
<div class="price">R$ 0,01</div>
</div>
</div>
See also: Center inline-blocks with dynamic width in CSS
This is one way to center anything within a div not know the inner width of the elements.
#product_15{
position: relative;
margin: 0 auto;
display: table;
}
.price, img{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
my solution was:
.parent {
display: flex;
flex-wrap: wrap;
}
.product {
width: 240px;
margin-left: auto;
height: 127px;
margin-right: auto;
}
add this css to your product_container class
margin: 0px auto;
padding: 0px;
border:0;
width: 700px;