The height and width of the elements can be set by the respective namesake properties. The values can be set as any of the following three:
- auto : The default value calculated by the browser itself
- Length: Can be given in px, pt, cm etc.
- Percentage: As per the percentage of the containing block
Here’s an example for the same:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <!DOCTYPE html> <html> <head> <title>Page Title</title> <style> div.ex1 { height: auto; width: 300px; background-color: red; } div.ex2 { background-color: orange; height: 100px; width: 50%; } </style> </head> <body> <div class="ex1">div1</div><br/> <div class="ex2">div2</div> </body> </html> |
In the above example, the <div> element for class ex1 will have a width of 100px. The height of the <div> will be set by the browser depending on the content inside it.
Similarly, for a <div> element of class ex2, height will 20% of the containing block.
Please note, the height and width properties set the height and the width of the space inside the padding, margins and borders of the containing block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <!DOCTYPE html> <html> <head> <title>Page Title</title> <style> #first { height: 100px; width: 300px; background-color: yellow; } </style> </head> <body> <div id="first">hello</div> </body> </html> |
Max-Width
The maximum width of an element can be set using the max-width property. The allowed values are
- Length
- Percentage
- None(default value, meaning no maximum limit for width)
Example:
1 2 3 4 | .mw { max-width: 450px; background-color:#CACB96 ; } |
1 2 3 4 | .mw { max-width: 30%; background-color:#F8C471; } |
A noticeable of the advantage of using the max-width property is that unlike the simple width property, it can shrink or grow (up to the max-width value) as per the browser window.
So, in above example, if your browser window shrinks to a width less then 450px, the respective element will also shrink in width.
In a similar fashion we can set the minimum width and minimum/maximum height of the elements using the properties min-width, min-height, and max-height.
Based on the element content and the devices where it can be used, you choose from these properties.
Here’s an example for all of these:
1 2 3 4 5 6 7 | div { max-width: 500px; max-height: 300px; min-width: 100px; min-height: 100px; background-color: #BB8FCE;; } |
Run
Ideally, the element takes the max-width and the min-height value.