如何调整flex布局下两div宽度,使内部文本高度一致?
解决方案:让双列文本高度完全匹配的动态宽度调整
你的核心需求是让拉丁语列的文本内容高度与英语列完全一致,而非仅保证容器高度相同。由于CSS无法直接基于文本总高度计算容器宽度,需结合React的DOM操作动态调整:
实现思路
- 先让英语列以自然宽度渲染,获取其内部文本的真实总高度
- 逐步缩小拉丁语列的宽度,迫使文本换行增加高度,直到与英语列的文本高度匹配
- 监听窗口 resize 和内容变化,确保动态场景下布局依然有效
代码实现
React 组件代码
import { useEffect, useRef } from 'react'; const TextColumns = () => { const latinColRef = useRef(null); const englishColRef = useRef(null); useEffect(() => { const adjustLatinWidth = () => { if (!latinColRef.current || !englishColRef.current) return; // 获取英语列的文本总高度 const englishTextHeight = englishColRef.current.scrollHeight; // 重置拉丁语列宽度,获取初始状态 latinColRef.current.style.width = 'auto'; let currentLatinHeight = latinColRef.current.scrollHeight; // 高度已匹配则无需调整 if (currentLatinHeight === englishTextHeight) return; // 逐步缩小宽度,直到高度匹配(设置最小宽度避免过窄) let width = latinColRef.current.offsetWidth; while (currentLatinHeight < englishTextHeight && width > 50) { width -= 5; latinColRef.current.style.width = `${width}px`; currentLatinHeight = latinColRef.current.scrollHeight; } }; adjustLatinWidth(); // 监听窗口尺寸变化 window.addEventListener('resize', adjustLatinWidth); return () => window.removeEventListener('resize', adjustLatinWidth); }, []); return ( <div className="container"> <div className="column latin-column" ref={latinColRef} > <p>Gallia est omnis divisa in partes tres, quarum unam incolunt Belgae, aliam Aquitani, tertiam qui ipsorum lingua Celtae, nostra Galli appellantur. [2] Hi omnes lingua, institutis, legibus inter se differunt. Gallos ab Aquitanis Garumna flumen, a Belgis Matrona et Sequana dividit. [3] Horum omnium fortissimi sunt Belgae, propterea quod a cultu atque humanitate provinciae longissime absunt, minimeque ad eos mercatores saepe commeant atque ea quae ad effeminandos animos pertinent important, [4] proximique sunt Germanis, qui trans Rhenum incolunt, quibuscum continenter bellum gerunt. Qua de causa Helvetii quoque reliquos Gallos virtute praecedunt, quod fere cotidianis proeliis cum Germanis contendunt, cum aut suis finibus eos prohibent aut ipsi in eorum finibus bellum gerunt. [5] [Eorum una, pars, quam Gallos obtinere dictum est, initium capit a flumine Rhodano, continetur Garumna flumine, Oceano, finibus Belgarum, attingit etiam ab Sequanis et Helvetiis flumen Rhenum, vergit ad septentriones. [6] Belgae ab extremis Galliae finibus oriuntur, pertinent ad inferiorem partem fluminis Rheni, spectant in septentrionem et orientem solem. [7] Aquitania a Garumna flumine ad Pyrenaeos montes et eam partem Oceani quae est ad Hispaniam pertinet; spectat inter occasum solis et septentriones.</p> <p>Apud Helvetios longe nobilissimus fuit et ditissimus Orgetorix. Is M. Messala, [et P.] M. Pisone consulibus regni cupiditate inductus coniurationem nobilitatis fecit et civitati persuasit ut de finibus suis cum omnibus copiis exirent: [2] perfacile esse, cum virtute omnibus praestarent, totius Galliae imperio potiri. [3] Id hoc facilius iis persuasit, quod undique loci natura Helvetii continentur: una ex parte flumine Rheno latissimo atque altissimo, qui agrum Helvetium a Germanis dividit; altera ex parte monte Iura altissimo, qui est inter Sequanos et Helvetios; tertia lacu Lemanno et flumine Rhodano, qui provinciam nostram ab Helvetiis dividit. [4] His rebus fiebat ut et minus late vagarentur et minus facile finitimis bellum inferre possent; [5] qua ex parte homines bellandi cupidi magno dolore adficiebantur. [6] Pro multitudine autem hominum et pro gloria belli atque fortitudinis angustos se fines habere arbitrabantur, qui in longitudinem milia passuum CCXL, in latitudinem CLXXX patebant.</p> </div> <div className="column english-column" ref={englishColRef}> <p>All Gaul is divided into three parts, one of which the Belgae inhabit, the Aquitani another, those who in their own language are called Celts, in our Gauls, the third. All these differ from each other in language, customs and laws. The river Garonne separates the Gauls from the Aquitani; the Marne and the Seine separate them from the Belgae. Of all these, the Belgae are the bravest, because they are furthest from the civilization and refinement of our Province, and merchants least frequently resort to them, and import those things which tend to effeminate the mind; and they are the nearest to the Germans, who dwell beyond the Rhine , with whom they are continually waging war; for which reason the Helvetii also surpass the rest of the Gauls in valor, as they contend with the Germans in almost daily battles, when they either repel them from their own territories, or themselves wage war on their frontiers. One part of these, which it has been said that the Gauls occupy, takes its beginning at the river Rhone ; it is bounded by the river Garonne, the ocean, and the territories of the Belgae; it borders, too, on the side of the Sequani and the Helvetii, upon the river Rhine , and stretches toward the north. The Belgae rises from the extreme frontier of Gaul, extend to the lower part of the river Rhine ; and look toward the north and the rising sun. Aquitania extends from the river Garonne to the Pyrenaean mountains and to that part of the ocean which is near Spain: it looks between the setting of the sun, and the north star.</p> <p>Among the Helvetii, Orgetorix was by far the most distinguished and wealthy. He, when Marcus Messala and Marcus Piso were consuls [61 B.C.], incited by lust of sovereignty, formed a conspiracy among the nobility, and persuaded the people to go forth from their territories with all their possessions, [saying] that it would be very easy, since they excelled all in valor, to acquire the supremacy of the whole of Gaul. To this he the more easily persuaded them, because the Helvetii, are confined on every side by the nature of their situation; on one side by the Rhine , a very broad and deep river, which separates the Helvetian territory from the Germans; on a second side by the Jura , a very high mountain, which is situated between the Sequani and the Helvetii; on a third by the Lake of Geneva, and by the river Rhone, which separates our Province from the Helvetii. From these circumstances it resulted, that they could range less widely, and could less easily make war upon their neighbors; for which reason men fond of war as they were were affected with great regret. They thought, that considering the extent of their population, and their renown for warfare and bravery, they had but narrow limits, although they extended in length 240, and in breadth 180 Roman miles.</p> </div> </div> ); }; export default TextColumns;
CSS 样式
.container { display: flex; justify-content: center; gap: 20px; width: 1000px; margin: 0 auto; } .column { display: inline-block; flex: 0 1 auto; word-wrap: break-word; overflow-wrap: break-word; } .latin-column { width: auto; }
关键说明
- 使用
scrollHeight获取文本的真实总高度(包含所有换行后的内容) - 通过逐步缩小拉丁语列宽度,迫使文本换行以增加高度,直到与英语列匹配
- 设置50px最小宽度限制,避免列过窄影响可读性
- 监听窗口 resize,保证布局在窗口尺寸变化时依然有效
内容的提问来源于stack exchange,提问作者Shaun Evans




