When I set the background image for UL, why do I need to set the width and height when the children already have these settings?

I follow this tutorial on creating buttons with CSS. http://www.secondpicture.com/tutorials/web_design/css_ul_li_horizontal_css_menu.html

The background for the buttons is set in the UL element. I noticed that if you remove the height and width attributes of the UL element, the background image will disappear, as if the UL size reaches zero. This does not make sense to me in terms of the box model. Detail elements (LIs) are predefined and must stretch the UL dimension accordingly. Can someone explain what is happening?

ul { list-style-type: none; background-image: url(navi_bg.png); height: 80px; width: 663px; margin: auto; } 
+4
source share
3 answers

According to the manual, LIs are float: left, which means that they no longer take up space in the parent element (UL). To fix this problem, you will need clearfix, see this topic: What methods of using clearfix can I use?

+1
source

The <li> plugin is moved in such a way that they are removed from the document flow, which causes the <ul> fail.

To behave as you expect, try adding float: left; in <ul> .

+2
source

A good fix that I always use is to put <ul> in the <div> as such <div id="nav"><ul>...</ul></div> and then apply the background image to the <div> .

The best answer:

In CSS add display: table-row; into the ul element and display: table-cell; to the elements li . This is better than float: left , as it does not reset your parent element and display: inline-block , since it does not present an annoying gap between the elements.

0
source

Source: https://habr.com/ru/post/1398338/


All Articles