To size non-text HTML elements relative to their parent elements on the page you can use percentages.
Percentages are often used to size box-model values, like width and height, padding, border, and margins. They can also be used to set positioning properties (top, bottom, left, right).
To start, let’s size the height and width of an element using percentages.
.main { height: 300px; width: 500px; } .main .subsection { height: 50%; width: 50%; }
In the example above, .main
and .subsection
each represent divs. The .subsection
div is nested within the .main
div. Note that the dimensions of the parent div (.main
) have been set to a height of 300 pixels and a width of 500 pixels.
When percentages are used, elements are sized relative to the dimensions of their parent element (also known as a container). Therefore, the dimensions of the .subsection
div will be 150 pixels tall and 250 pixels wide. Be careful, a child element’s dimensions may be set erroneously if the dimensions of its parent element aren’t set first.
Note: Because the box model includes padding, borders, and margins, setting an element’s width
to 100%
may cause content to overflow its parent container. While tempting, 100%
should only be used when content will not have padding, border, or margin.
Instructions
Currently, the blog takes up the full width of the body. Let’s modify this so that it doesn’t extend to fill the full width.
In style.css, set the width in #blog
to 86%
.
This will responsively set the entire blog’s container to 86% of the full width of the body.
Great! Resize the browser’s width again. Notice that the blog’s text becomes illegible at smaller widths.
To fix this, set the width in #blog .post
to 52%
.
This will ensure that the text fills only 52% of its container’s (#blog
) width. Resize the browser now and notice how the text remains legible.
Now set the width in .post .image-container
to 100%
. This will make sure the image’s container is always the full width of the blog post (.post
).
Scroll to the bottom of the web page. Notice that there are two images. We’d like to display these images next to each other on the page, with equal width.
Set the width in .images .image-container
to 50%
. This will give each image in .images
equal width.
Don’t worry if the images still look distorted at the moment. You’ll improve their appearance in a later exercise.