我正在尝试为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/
我在做什么错?
为了使列表项的宽度取决于文本,请从display
和ul
中删除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?