How can I make the first li tag have the same width as the contents?
How can I make the other li tags have the same width as the first one?
I need the overflow-auto in the parent to show the horizontal scrollbar.
Is it possible to achieve this with pure CSS? and using tailwind?
<script src="https://cdn.tailwindcss.com"></script>
<ul class="overflow-x-auto w-32">
<li class="bg-blue-50 whitespace-nowrap">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eget hendrerit nibh.
</li>
<li class="bg-red-50 whitespace-nowrap">foo</li>
<li class="bg-green-50 whitespace-nowrap">bar</li>
<li class="bg-orange-50 whitespace-nowrap">baz</li>
<ul>
2
Answers
I found the solution without js:
1. Set
inline-block
display for the<li>
tags: This allows each<li>
tooccupy only the necessary
width
based on its contents.2. Calculate the
width
of the first<li>
tag dynamically:Use JavaScript to get the width of the first
<li>
tag after it has been rendered and then apply thatwidth
to all other<li>
tags.Here is how you can modify your code and add some JavaScript to achieve this:
In this code:
I’ve added the
inline-block
class to each<li>
element to make them inline-block elements, so they take up only as much width as necessary/content.I’ve wrapped the
<li>
elements inside a<ul>
element withoverflow-x-auto
andmax-w-full
classes to enable horizontal scrolling and ensure the list takes up the full width of its container.NOTE: JavaScript code calculates the width of the first
<li>
element and then applies that width to all other<li>
elements, ensuring they have the same width.I executed the code and go this output:
li and other having same width and horizontal scroll
and after adding more content to first
<li>
got the following output as:after adding content & scroll proof
Like it if you find it helpful so others can use it too.
Happy Coding and have a good day❤️