Dan Dan - 5 months ago 11
CSS Question

Why does style in <ul> only affect the first <li>?

I have a

unordered list
in my code which looks a little like this



.tntext {
display: inline-block;
list-style-type: none;
padding: 0;
margin: 0;
text-align: center;
height: 40px;
line-height: 40px;
font-size: 20px;
width: 150px;
background-color: red;
}

<ul class="tntext">
<li>hi</li>
<li>hi</li>
<li>hi</li>
<li>hi</li>
</ul>





This produces a list which looks like the picture below. You can see the code at this JSFiddle

enter image description here

However when the html is changed to something which looks like this



.tntext {
display: inline-block;
list-style-type: none;
padding: 0;
margin: 0;
text-align: center;
height: 40px;
line-height: 40px;
font-size: 20px;
width: 150px;
background-color: red;
}

<ul>
<li class="tntext">hi</li>
<li class="tntext">hi</li>
<li class="tntext">hi</li>
<li class="tntext">hi</li>
</ul>





This produces a list which looks like the picture below. You can see the code at this JSFiddle

enter image description here

Why does declaring the class in the
<ul>
tag only affect the first
<li>
child inside the
<ul>
tag?

Answer

It's actually not "technically" affecting the <li> tags underneath it, but actually the first <li> and the <ul> are overlapping. The reason for this is because you are not defining the style for each of the <li> tags and so they are forced to inherit styles from their parent, the .tntext class. They inherit the width and the height, hence why the first <li> is overlapping with the <ul> tag; they both have the same height/width. Check these pictures out to see what I mean

enter image description hereenter image description here

If you remove the height css value from the <ul> tag, you will see the entire list turn red (Like so: https://jsfiddle.net/ntvcsese/ ). If you want to apply every style from that class to each <li> tag instead, you have to change .tntext to .tntext li in your css. Like so: https://jsfiddle.net/fhxqLboL/1/

Comments