CSS Height and Width
The width and height properties set the size of the content area of an element. Block elements are as wide as their parent by default, and as tall as their content.
.box {
width: 300px;
height: 100px;
background: lightgreen;
}
Output in the browser
300px x 100px
Width in percent
A percentage is calculated from the width of the parent.
.half { width: 50%; }
max-width and min-width
A fixed width can break the layout on a small phone, because the box cannot shrink. Use max-width: the box can be smaller, but never bigger than the limit.
.container {
width: 100%;
max-width: 960px;
margin: 0 auto; /* centre the box */
}
max-widthsets the biggest width.min-widthsets the smallest width.max-heightandmin-heightdo the same for height.
Height
Avoid giving a fixed height to boxes with text. If the text grows, it will come out of the box. Use min-height instead.
.section { min-height: 200px; }
.full { height: 100vh; } /* full screen height */
Note:
By default width does not include padding and border, so a box with width: 200px and padding: 20px becomes 240px wide. Fix this with box-sizing: border-box. See CSS Box Model.
Summary
widthandheightset the size.- Prefer
max-widthandmin-heightfor flexible layouts. - Centre a box with
margin: 0 autoand a width. - Next: CSS Padding.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |