gpt4 book ai didi

css - ul 内每个 li 的宽度不同

转载 作者:行者123 更新时间:2023-12-04 10:36:57 30 4
gpt4 key购买 nike

我试图为每个 li 获得不同的宽度里面的元素 ul ,但是一旦我添加一个更大的元素,所有 li得到相同的宽度。我想要 li s 的宽度与文本长度相同。

我的 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: leftli元素。如果要将每个列表项都放在一个新行中,请添加 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: autoul .更多相关信息: What methods of ‘clearfix’ can I use?

关于css - ul 内每个 li 的宽度不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60131262/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com