218

I was asked a question in an interview that "what is the difference between the css height:100% and height:auto?"

Can any one explain?

bash.d
  • 13,029
  • 3
  • 29
  • 42
Gowsikan
  • 5,571
  • 8
  • 33
  • 43

4 Answers4

309

height: 100% gives the element 100% height of its parent container.

height: auto means the element height will depend upon the height of its children.

Consider these examples:

height: 100%

<div style="height: 50px">
    <div id="innerDiv" style="height: 100%">
    </div>
</div>

#innerDiv is going to have height: 50px

height: auto

<div style="height: 50px">
    <div id="innerDiv" style="height: auto">
          <div id="evenInner" style="height: 10px">
          </div>
    </div>
</div>

#innerDiv is going to have height: 10px

Ninjakannon
  • 3,751
  • 7
  • 53
  • 76
Manish Mishra
  • 12,163
  • 5
  • 35
  • 59
  • 10
    I think that in the case of 'height:auto #innerDiv will be `10px + the size it needs for its own content` - see this [jsfiddle](https://jsfiddle.net/wf0zo5bu/) – BornToCode Sep 06 '15 at 13:14
  • 1
    @Manish Mishra: What is the best responsive design? Setting the height of the child element or the container element, and letting the other to derive its height ? – John Strood Jun 16 '16 at 09:29
  • 2
    I think a good way of thinking about auto is that you are 'unsetting' hight - it's like not having it set. – niico Oct 06 '16 at 18:16
  • 2
    I modified the fiddle that BornToCode shared above, to make it more obvious that `auto` causes the element to grow to accomodate BOTH its content, AND its child's content. In contrast a Fixed height value does not grow (or show) content that cannot fit within the declared height.https://jsfiddle.net/m3f8y6xr/1/ This Answer, I believe, is not sufficiently worded to make it ovbious that the element will grow to include all content, whether it is its own text, or a child's content. Of course it can be argued that its own text is also a child. This provides visual confirmation of the behavior. – SherylHohman Apr 02 '19 at 19:00
7

A height of 100% for is, presumably, the height of your browser's inner window, because that is the height of its parent, the page. An auto height will be the minimum height of necessary to contain .

John Dvorak
  • 26,799
  • 13
  • 69
  • 83
Rohit Azad Malik
  • 31,410
  • 17
  • 69
  • 97
  • 4
    This isn't necessarily correct if the parent element is one with a defined height that doesn't fit to the size of the browser's window – goonerify Apr 30 '16 at 06:05
7

height:100% works if the parent container has a specified height property else, it won't work

Chukwuemeka
  • 136
  • 1
  • 6
3

The default is height: auto in browser, but height: X% Defines the height in percentage of the containing block.

Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100