Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different width for each li inside ul

Tags:

css

html-lists

I'm trying to get a different width for each li element inside ul, but as soon as I add a larger element all the li get the same width. I want the lis have the same width as the text length.

My HTML:

<div>
 <ul>

 </ul>
</div>
<textarea></textarea>
<button>Send</button>

My CSS:

div{
    overflow-y: scroll;
    overflow-x: hidden;
    height: 400px; 
    width:400px;
    border:1px solid black;
}
div ul {
    display: table;
    list-style: none;
}
div ul li{
    display: block;
    background-color: #b70505;
    color: white;
    font-weight: 600;
    font-size: 0.8em;
    border-radius: 25px;
    margin-top: 5px;
    padding: 10px;
    max-width:200px;
    word-wrap:break-word;
}

My JS:

var box = document.getElementsByTagName('div')[0];
var newText = document.getElementsByTagName('textarea')[0];
var button = document.getElementsByTagName('button')[0];

button.addEventListener('click', function(e){
    e.preventDefault();
    if(newText.value !== ''){
        var Newitem = document.createElement('li');
        Newitem.innerHTML = newText.value;
        box.getElementsByTagName('ul')[0].appendChild(Newitem);
        box.scrollTop = box.scrollHeight;
    }
});

https://jsfiddle.net/hdr60zmb/

What am I doing wrong?

like image 525
epselonzero Avatar asked Nov 21 '25 06:11

epselonzero


1 Answers

In order to make list items width dependent from text, remove display attributes from ul and li and just set float: left to li elements. If you want to have each list item in a new line, add clear: left.

CSS:

div ul {
    list-style: none;
}

div ul li {
    float: left;
    clear: left;
    background-color: #b70505;
    color: white;
    font-weight: 600;
    font-size: 0.8em;
    border-radius: 25px;
    margin-top: 5px;
    padding: 10px;
    max-width: 200px;
    word-wrap: break-word;
}

Demo: https://jsfiddle.net/rwkb03xc/

Remember about clearfixing the ul, to keep height of that element. The simplest solution is to add overflow: auto to ul. More on this: What methods of ‘clearfix’ can I use?

like image 132
EMiDU Avatar answered Nov 24 '25 03:11

EMiDU



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!