ul中每个li的不同宽度

问题描述 投票:0回答:1

我正在尝试为li中的每个ul元素获得不同的宽度,但是一旦我添加了更大的元素,所有的li就会获得相同的宽度。我希望li的宽度与文本长度相同。

我的HTML:

<div>
 <ul>

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

我的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;
}

我的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/

我在做什么错?

css html-lists
1个回答
0
投票

为了使列表项的宽度取决于文本,请从displayul中删除li属性,然后将float: left设置为li元素。如果要使每个列表项都换行,请添加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;
}

演示:https://jsfiddle.net/rwkb03xc/

[有关固定ul的注意事项,以保持该元素的高度。最简单的解决方案是将overflow: auto添加到ul。有关此的更多信息:What methods of ‘clearfix’ can I use?

© www.soinside.com 2019 - 2024. All rights reserved.