I’m still a beginner for web development.For a section in html, an image was set as the background and height was given in css as 100% to take full height also width was give as 50%. Without any text in that section image is not showing.
With text it covers just the row needed for text.When height given in pixels image shows again.What could be the error?
3
Answers
It is not because of text. Because of height.
We cannot use height=100% for full screen height. Use
height=100vh
instead.When you are giving height in % the section takes the minimum height required for the text and hence the image comes for one row .
But as soon as you specify the height in pixels it is a predefined height for the section and is not dependent on the text hence you can see the image.
So you have to give height=100vh due to which the section will cover the whole screen height even if there is no text in it.
Updated to address percentage value calculation
height
of%
value is calculated based on its parentWhen using a
%
value for aheight
, according to MDN docThat is, unless its parent has an explicit height, the child cannot determine the
%
value. Conversely, when you setheight: 100%
, you’re saying "100% of the parent height," and without explicit parent height, it becomesheight: auto
which then collapses without its own child content or explicit height.Block-level container collapses unless it has content or specific height
By default, any
div
,section
, or other block-level containers will collapse their height to0
unless it has some content. Also, whatever background image you set up will also not show up, because the container is not rendered.If there’s small amount of text (e.g. one line of text), the container will grow only so much, so that the container can envelop the content inside. The background image will show through the given height of the container.
To address this behavior, you could:
min-height
to set a minimum height even when there’s no to little content, and will grow as needed if the content is biggerheight
to set a fixed value of height regardless of the amount of content,position
values to place other content in front of the image.See the code snippet below.
By default all
section
has the default50%
height value as you noted. Also, each block has a colored border to show its area.height
ormin-height
. This collapses to0px
height by default.min-height
to ensure a minimum space. As you add more content here, the container will grow as needed.height
value to100vh
. This will stay static value, whether you have no content, little content, or a crazy amount of content inside.