masoud soroush
masoud soroush

Reputation: 677

How to center element inside of a div

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/

Upvotes: 2

Views: 483

Answers (4)

masoud soroush
masoud soroush

Reputation: 677

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

Upvotes: 0

Hedron Dantas
Hedron Dantas

Reputation: 656

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

Upvotes: 0

Ollie
Ollie

Reputation: 207

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;
} 

Upvotes: 0

Mohammad Masoudian
Mohammad Masoudian

Reputation: 3501

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

Upvotes: 1

Related Questions