Reputation: 151
I'm trying to position a div centered in another div with this code:
<div style="width:100%; height: 300px; background:red;">
<div style="margin:auto; min-width:50%; height:100%; background:green;">Text</div>
</div>
It results in a big green div that's width is 100%. I expect it to be 50% though. Can somebody tell me why css wont give it 50% width and center it?
Upvotes: 2
Views: 4196
Reputation: 1397
Updated answer
<div style="width:100%; height: 300px; background:red; text-align: center">
<div style="min-width:50%; display: inline-block; height:100%; background:green;">Text</div>
</div>
Upvotes: 4
Reputation: 114990
The answer lies in the term minimum width...it's a minimum. The default width of a block level element is 100% so it's already over 50% and thus expands to full width.
You need to change the display property to inline-block
and then use text-align:center
on the parent to center the child.
.parent {
width: 100%;
height: 300px;
background: red;
text-align: center;
}
.child {
display: inline-block;
min-width: 50%;
height: 100%;
background: green;
}
<div class="parent">
<div class="child">Text</div>
</div>
Upvotes: 1
Reputation: 722
The parent div where you set width to 100% dictates that the content of the div should consume 100% of the width. The inner div says make sure that this div has a minimum width of 50%. If you would like to center and fix the width to 50% try something like
<div style="margin:auto; width:50%; height:100%; background:green;
margin-left: auto ;margin-right: auto;">Text</div>
http://www.thesitewizard.com/css/center-div-block.shtml
Upvotes: 0