Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force parent div to expand by child div width/padding/margin/box?

Tags:

html

css

I want to expand div parent with child div but I don't know if that's possible and how to do it.

enter image description here

I prepare a fiddle and included some code.

CSS

body {     background: gray; } div.page {     color: white;     background: black;     max-width: 72em;     margin: auto;     padding: 1em; } div.one {     background-color: red;     width: 40%; } div.two {     background-color: green;     width: 120%; } 

HTML

<body>     <div class="page">         <div class="one">One</div>         <div class="two">Two</div>     </div> </body> 
like image 700
Chameleon Avatar asked Jun 25 '13 07:06

Chameleon


People also ask

How do you make a child div expand with their parents?

You can try adding a fixed height to the parent which might work or put enough content in the child to stretch it; that will work. Show activity on this post. You have margin-bottom set on both elements. With the child having a bottom margin, it will always be smaller by that amount.

How do I make my div 100 height relative to parents?

Answer: Set the 100% height for parents too If you will try the set the height of a div container to 100% of the browser window using the style rule height: 100%; it doesn't work, because the percentage (%) is a relative unit so the resulting height depends on the height of parent element's height.

How do you make a div wider as its content?

You can simply use the CSS display property with the value inline-block to make a <div> not larger than its contents (i.e. only expand to as wide as its contents).


2 Answers

The key solution to your problem is to use display:inline-block;

HTML

body {     background: gray; } div.page {     color: white;     background: black;     margin: auto;     padding: 1em;     display:inline-block; } div.one {     background-color: red;     width: 10em;     display:inline-block; } div.two {     background-color: green;     width: 40em;     display:inline-block; }
<div class="page">   <div class="one">One</div>   <div class="two">Two</div> </div>
like image 95
bot Avatar answered Sep 22 '22 00:09

bot


You cannot use % and expect box to overflow, else it never ends 100% turns 120%, but then 120% of 120%, becomes .. and so on. forget this idea, it cannot work.

Your CSS request is incoherent.

Beside, to see an element to grow wider than window, one of the parent must be able to behave this way, mostly , content overflow and remain visible. (html/body or parent)

as far as i know only:

display: 
  1. table
  2. inline-table
  3. table-row
  4. table-cell

Can let container grow as much as content does.

like image 28
G-Cyrillus Avatar answered Sep 22 '22 00:09

G-Cyrillus