html - Making one element's width dependent upon its sibling's width -
i'm trying make widget such subtitle can never longer title. title control width of widget, , subtitle wrap if got wider title. , i'm trying without javascript if possible.
i got close (see snippet below). able make subtitle artificially short, in case, row it's in reason expanded fit whole space of container, instead of space used child! in fact, space took if weren't wrapped.
#container { background: #ddd; display: flex; flex-direction: column; align-items: flex-start; } .row { display: flex; } #subtitle { flex-basis: 0; }
<div id="container"> <div class="row"> <h1 id="title">title long</h1> </div> <div class="row"> <h3 id="subtitle">subtitle long subtitle , longer , oh super!</h3> </div> </div>
i need keep subtitle in flow (not position:absolute
), , title needs able wrap if gets super long (so won't spill off page). there way have 2 rows, 1 below other, , 1 can ever long other 1 is?
sounds css table me:
#container { background: #ddd; display: table; width: 100%; } .row { display: table-row; } .row > * { display: table-cell; } .row:after { content: " "; display: table-cell; } #title { width: 1px; white-space: nowrap; }
<div id="container"> <div class="row"> <h1 id="title">title long</h1> </div> <div class="row"> <h3 id="subtitle">subtitle long subtitle , longer , oh super!</h3> </div> </div>
width:1px
on title causes column collapse. white-space:nowrap
prevents title wrapping. since it's using table layout, combination causes width of column determined title , subtitle follows along. :after
provides flexible column fill out table.
(once css grid becomes available, might preferable.)
you mentioned long titles. possibility, you'll need switch javascript. (the javascript below needs either somewhere after section being affected or run on page load.)
var title = document.getelementbyid('title'), subtitle = document.getelementbyid('subtitle'), subtitleresize = function() { subtitle.style.width = title.clientwidth + 'px'; }; window.addeventlistener('resize', subtitleresize, false); subtitleresize();
#container { background: #ddd; } #title { display:inline-block; }
<div id="container"> <div class="row"> <h1 id="title">title long</h1> </div> <div class="row"> <h3 id="subtitle">subtitle long subtitle , longer , oh super!</h3> </div> </div>
Comments
Post a Comment