Reputation: 28555
There are a lot of questions regarding forcing a nested div child to fill the width of its parent container, but my question is how to force a child div with a natural flow width that is larger than its parent container (for example, the child div contains a text node that ends up stretching the child beyond the width of the parent container) to maintain its parents width?
A simple non-dynamic solution is to set a width on the parent, but what if the width is not pre-determined (for responsive reasons)? Is there some tag I can add to the child elements to make sure they wrap their content and force the element to stay within the width of the parent?`
<div class="parent"> //Width is not set
<div class="child">Here might be a long string of dynamic text</div>
</div>
I understand that by setting a width on the parent element would fix this issue, but in my case I cannot do that because the element is set to resize its width depending on screen size. So for instance if the user is on a phone and turns from portrait to landscape, the parent element must be able to resize and i'd prefer to not have to use javascript for that.
I should also mention that in my particular situation, the parent element is a float. I'm not sure if that matters or not.
Upvotes: 2
Views: 4023
Reputation: 28555
Per Sheikh Heera's comment on the question, the only way to achieve this is by actually setting a width on the parent element. In my situation the most robust solution was to use media queries to set the width per the screen size accordingly. Its not exactly the solution i'd like, but its the best alternative.
Upvotes: 1
Reputation: 2660
is this what you want to achieve.
css
.parent {float:left; width:100%}
.child {display:block}
working demo
hope this help..
Upvotes: 0
Reputation: 470
You can contain the child size within the parent by using overflow style:
.parent {
overflow: hidden;
}
.child {
width: 100%;
}
Upvotes: 0
Reputation: 53
Why not use the max-width CSS property? Div, specifically the child here, is a block level element and should confine itself to the parent div's width. If the code below doesn't help we will need you to expand on what you are working on.
.child {
max-width: 100%
}
Try that in your stylesheet and behold the css magic! Cheers
Upvotes: 1