I am trying to center my div responsively. But I am unable to do it without setting a width...
<div class="wrapper">
<div class="container">
<div class="left box">Content</div>
<div class="right box">Content</div>
</div>
</div>
.wrapper {text-align:center}
.container {width:100%; margin: 10px auto}
.left {width:69%;max-width:350px; background:blue}
.right {width:29%;max-width:150px; background:red}
.box {float:left;padding:20px}
How can I keep the .container
in the middle ?
Demo: http://jsfiddle.net/z9zydnwL/
Using the Position, Top, Left, and Transform Properties To horizontally and vertically center a div within a div whose height and width is unknown, you can use the transform property instead of the margin property. You'll still use the CSS position, top, and left properties.
Simply give the child element a property of margin: with a value of 0 auto; . This will automatically size the margin on the left and right sides of the div evenly to one another.
Div is basically BLOCK with FULL-WIDTH (100%) so set margin:auto is doesn't get anything since the width is full to the parent. To make it work, you can did that by 2 ways, use text-align:center for div -> this will align text inside div center. include width property in div (i.e. width:200px) and it will work fine.
Flexbox can even center floated children!
So I can simply add display:flex
and justify-content: center;
to the container
.container {
margin: 10px auto;
display:flex;
justify-content: center; /* align horizontal */
}
FIDDLE
Browser support these days is also good
.wrapper {
width: 100%;
text-align: center
}
.container {
margin: 10px auto;
display: flex;
justify-content: center;
/* align horizontal */
}
.left {
width: 69%;
max-width: 350px;
background: blue
}
.right {
width: 29%;
max-width: 150px;
background: red
}
.box {
float: left;
padding: 20px
}
<div class="wrapper">
<div class="container">
<div class="left box">Content</div>
<div class="right box">Content</div>
</div>
</div>
One solution is to replace float with inline-block:
.wrapper {
text-align: center
}
.container {
margin: 10px auto;
font-size: 0;
}
.left {
width: 69%;
max-width: 350px;
background: blue
}
.right {
width: 29%;
max-width: 150px;
background: red
}
.box {
display: inline-block;
padding: 20px;
font-size: 16px;
}
<div class="wrapper">
<div class="container">
<div class="left box">Content</div>
<div class="right box">Content</div>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With