2

I want to center the content of .SideBarFirst div but don't know how to achieve this.

Can someone help me out with an solution which is not based on adding padding or left/right values to the element?

body {
    width: 960px;
    margin: 0 auto;
} 

.content {
    width:500px; 
    float: left;
}

.SideBarFirst {
    width:460px; 
    float: right;
}

.SideBarFirst div {
    width: 40px;
    margin: 0 auto; 
}
<body>
    <div class="content">test</div>
    <div class="SideBarFirst">
        <div>not working for center</div>
    </div>
</body>

My current code: http://jsfiddle.net/21sxvg4L/

Stacks Queue
  • 848
  • 7
  • 18
masoud soroush
  • 677
  • 11
  • 21

4 Answers4

1

just remove this:

body {
    width: 960px;
    margin: 0 auto;
} 

use this:

HTML

<div class="content">test</div>
<div class="SideBarFirst">
    <div>not working for center</div>
</div>

CSS:

.content {width:500px; float : left;}

.SideBarFirst {width:460px; float : right;}

.SideBarFirst div {
    width: 40px;
    margin: 0 auto; 
}

See This Fiddle

Mohammad Masoudian
  • 3,483
  • 7
  • 27
  • 45
0

YOu can use %

.SideBarFirst div {
    width: 40px;
    margin: 0 50%; 
}

Or you can be more brute and try this:

.SideBarFirst div {
    width: 40px;
    margin-left: 210px; 
}

Elastic layout will not work right with the this second code

Or this:

<div class="content">test</div>
<div class="SideBarFirst">
    <div align="center">not working for center</div>
</div>

Look this too: How to horizontally center a <div> in another <div>?

Community
  • 1
  • 1
Hedron Dantas
  • 616
  • 2
  • 6
  • 16
0

Your problem is that you are floating the element to the left so that it will always appear on the left. If you wan to center it change your css to this:

.content {width:500px; float : left;}

.SideBarFirst {width:460px; float : right;}

.SideBarFirst div {
    width: 40px;
    margin: 0 auto; 
}

Also remove this:

body {
    width: 960px;
    margin: 0 auto;
} 
Ollie
  • 207
  • 4
  • 13
0

this days problem solved with the display flex

.SideBarFirst {
    width:460px; 
    float: right;
    display: flex;
    align-items: center;
    justify-content: center;
}

by the way we can't apply margin or width to the body

masoud soroush
  • 677
  • 11
  • 21