Need some help with your project? Contact me

Issues with the width and height of CSS container and child elements

There are a couple of neat CSS tricks for displaying a parent DIV as high as the highest child element and to display the parent DIV only as wide as the child elements occupy inside. It can be quite annoying if you don't know about this.

Issue one

You have a div (div1) with two other divs (div2 and div3) inside. div2 floats left and consequently div3 goes up on the right. But what if you want the parent (div1) to have a border? You’ll see that it will drop the height because the child elements are floating.

What you have to do in this case, to maintain the parent element as high as the child elements – in order to display the border nicely around the children – is apply the following css to the parent div:

overflow: auto;
width: 100%;

Instead of overflow:auto, you can use any other overflow you want (like hidden) and you must declare the width. Note: some browsers also require the height to be declared. You can find more information on this solution here.

Issue two

You have a div container and a child element. The child div has a width of 400px but the parent has no width declared. Again, if you add a border, it can happen that the parent div is expanded to 100% while the child div is only 400px. You however may want it to be as wide as the child element – 400px (plus any paddings or margins declared). What you do is add the following css to the parent div:

display:inline-block;

Now, the width of the parent will be only as big as the width of the child.

Hope this helps.

Some related articles you might enjoy

Comments

Hi this solution is fine but i need this to be in different scenario

for eg:

my issue is width of parent div 1 should be based on width of child div 1 like that i want this for rest of the elements. can you help me as soon as possible.

Thank you Danny. It helped.

I have percentage with for floating children of a container and it seems to take up the complete width of the window when using display:inline-block.

Example:


Testing Child 1 Testing Child 2

Thanks ! it worked like heaven for me.

helped me out

In my case, that's the parent's height which is not declared, and i'd like it to fit his child's. Any idea ?

Text-align:center; will work for the height

You solved my problem! Thanks!

Add new comment

You can post comments in Markdown and basic HTML tags.
For code blocks, wrap your code within '~~~'. For example:
~~~
$var = 'my variable';
~~~