简体   繁体   中英

How to set all flex elements with the same width which adapts to the longest text?

I have two groups of checkboxes, each checkbox with a "ring" when mouse hover (i just simplified this in the code below, the ring shows directly, anyway it's not that much important.)

the thing is I need to keep all the checkbox row with the same width, which the width should adapt to the longest text one as well, so all "ring" looks same. (in this case, all the width of the 4 rings the width should be the same as the checkbox1)

 .group { display: flex; flex-direction: column; }.checkbox { border: 2px solid red; border-radius: 6px; width: fit-content; }
 <div class="group"> <h2>Group 1</h2> <div class="checkbox"><input type="checkbox" id="checkbox1"><label for="checkbox1">checkbox1 super super long texttexttexttexttexttexttexttexttexttext</label></div> <div class="checkbox"><input type="checkbox" id="checkbox2"><label for="checkbox2">checkbox2</label></div> </div> <div class="group"> <h2>Group 2</h2> <div class="checkbox"><input type="checkbox" id="checkbox3"><label for="checkbox3">checkbox3 abcdabcdabcd abcdabcdabcdabcd</label></div> <div class="checkbox"><input type="checkbox" id="checkbox4"><label for="checkbox4">checkbox4 abcdabcdabcd</label></div> </div>

Is there anyway to implement it? (can't set a fixed value, the text length is dynamic)

You should assign width: fit-content to the parent container, not the children.

Also I changed all the inline styles into external styles for better visualization:

 .group { display: flex; flex-direction: column; width: fit-content; }.input-group { border: 2px solid red; border-radius: 6px; }
 <div class="group"> <h2>Group 1</h2> <div class="input-group"> <input type="checkbox" id="checkbox1" /> <label for="checkbox1">checkbox1 super super long texttexttexttexttexttexttexttexttexttext</label> </div> <div class="input-group"> <input type="checkbox" id="checkbox2" /> <label for="checkbox2">checkbox2</label> </div> </div> <div class="group"> <h2>Group 2</h2> <div class="input-group"> <input type="checkbox" id="checkbox3" /> <label for="checkbox3">checkbox3 abcdabcdabcd abcdabcdabcdabcd</label> </div> <div class="input-group"> <input type="checkbox" id="checkbox4" /> <label for="checkbox4">checkbox4 abcdabcdabcd</label> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM