Mark VY Mark VY - 2 months ago 6
Javascript Question

Make list the width of an input tag without javascript

Consider the following snippet of HTML:

<input><ul>


We have an input tag, followed by a list. (The list will have actual items, but to keep things compact I left them out here.) Now, it is possible to control the width of the list using CSS, and likewise for the input tag.

I want to leave the input tag at its default width, and then make list width have a matching width. I could of course use JavaScript's getComputedStyle. In theory, this would cause problems if the user disables JavaScript, but in practice, I'm actually coding a (very minimalistic) autocomplete widget (like on Wikipedia, but less fancy), so it won't work without JavaScript anyway.

But still: is this possible? I know basically nothing about CSS, so forgive me if this is supposed to be obvious.

Answer

If you're not too averse to using newer CSS standards, I'd suggest using flexbox. It adapts both ways making sure both elements are the same width without having to set or calculate explicit values.

.wrapper {
  display: inline-flex;
  flex-direction: column;
}

/* for demo only */
ul{list-style-type:none;padding:0;margin:0;background:#ae0}.wrapper{margin-bottom:1em;}
<div class="wrapper">
  <input>
  <ul>
    <li>test 1</li>
    <li>test 2</li>
    <li>test 3</li>
  </ul>
</div>
<br>
<div class="wrapper">
  <input>
  <ul>
    <li>test 1</li>
    <li>test 2 tetts 3 stsdgsdf stsdgsdf</li>
    <li>test 3</li>
  </ul>
</div>

Comments