Center Div Within A Div?
I need help in centering one DIV withing a DIV. I want to have one container DIV that is auto width to take up the whole width of the screen (lets call it headerContainer. Within
Solution 1:
CSS:
.leftDiv{
float: left;
width: 400px;
}
.rightDiv{
float: right;
width: 200px;
}
.centerDiv{
width: 100px;
margin: 0 auto;
}
HTML:
<div><divclass="leftDiv">left</div><divclass="rightDiv">right</div><divclass="centerDiv">center</div></div>
DEMO:
Code: http://jsfiddle.net/Xxwrm/6/
Fullscreen: http://jsfiddle.net/Xxwrm/6/show
Solution 2:
This works.
.headerContainer{
width:auto !important;
}
.leftDiv{
float:left;
width:400px;
}
.rightDiv{
float:right;
width:200px;
}
.centerDiv{
display:inline;
width:100px;
margin-left:auto;
margin-right:auto;
}
.
<divclass="headerContainer"><divclass="leftDiv"></div><divclass="centerDiv"></div><divclass="rightDiv"></div></div>
Solution 3:
What you could do is add another div at the end which makes both sides equal, and set visibility: hidden;
(not display: none;
); this way it would centre the middle div.
For example in this case you'd have one @ 400px, another @ 100px, another @ 200px and another one, hidden, @ 200px.
Regards, Richard
Solution 4:
<divclass="headerContainer"><divclass="leftDiv">left</div><divclass="rightDiv">right</div><divclass="centerDiv">center</div></div>
This HTML with this CSS will work. I colored the DIV
's to make it obvious.
.headerContainer{
width:auto;
}
.leftDiv{
float:left;
width:400px;
background:pink;
}
.centerDiv{
width:100px;
/*
margin-left:auto;
margin-right:auto;
*/margin:0 auto;
background:cyan;
}
.rightDiv{
float:right;
width:200px;
background:lightgray;
}
However, if the screen is not 700px
wide, you will get some wrapping.
Here is a fiddle for it, too: http://jsfiddle.net/johnpapa/9bN2p/
Solution 5:
You can use a modern solution due the flex concept of css3.
.parent {
display: flex;
height: 300px;
/* Or whatever */background-color: green;
}
.child {
width: 100px;
/* Or whatever */height: 100px;
/* Or whatever */margin: auto;
/* Magic! */background-color: yellow;
}
<divclass="parent"><divclass="child ">Div1</div></div>
Post a Comment for "Center Div Within A Div?"