Search code examples
htmlcss

Display: inline-block for a list


I want to create a list that should look like this

Few Clouds
Humidity: 33%
Wind: 5.1 mph

However, because I'm using JS to insert <li> elements , I have to pre-write some parts of the list like this (excluding the [JS] part):

[JS]
Humidity: [JS]%
Wind: [JS] mph

Here's my code to solve this:

.inline {
  display: inline-block;
}
<ul class="list-unstyled">
  <li class="clouds text-capitalize inline"> </li>
  <span class="inline">Humidity: </span>
  <li class="wind inline"> </li><span class="inline">%</span>
  <span class="inline">Wind: </span>
  <li class="humidity inline"> </li><span class="inline">mph</span>
</ul>

but this results in (after the javascript plugs in data)

Few Clouds Humidity: 5.82 % Wind: 100mph

which is expected, but I dont know how to fix it so it looks like how I wanted in the first snippet. Ignore the other classes, they're bootstrap classes and classes for me to access them in javascript. Thank you for any help.


Solution

  • The only valid child of <ul> is <li>. Your <span> tags should go inside your <li> tags, not the other way around. I'd also recommend creating a second <span> tag inside each <li> to cover the JavaScript components. Considering <span> tags are inline by default, the pair of <span> tags will display next to each other on the same line.

    This can be seen in the following:

    var elements = document.getElementsByClassName('javascript');
    
    for (var i = 0; i < elements.length; i++) {
      elements[i].innerHTML = i;
    }
    <ul class="list-unstyled">
      <li class="clouds text-capitalize inline">
        <span class="inline">Humidity: </span>
        <span class="javascript"></span></li>
      <li class="wind inline">
        <span class="inline">Wind %: </span>
        <span class="javascript"></span>
      </li>
      <li class="humidity inline">
        <span class="inline">mph: </span>
        <span class="javascript"></span>
      </li>
    </ul>

    Note that if you want all three components to display on the same line, you could set the <li> elements to display: inline-block with:

    li {
      display: inline-block;
    }
    

    ...Though that would essentially defeat the purpose of using an <li> element in the first place.

    Hope this helps! :)