Make width of all elements equal based on widest one
This behaviour can be achieved using tables, like with this code:
<style>
table {
table-layout:fixed;
width:100%;
}
td {border:1px solid red;}
</style>
<table>
<tr>
<td>Hello</td>
<td>WWWWWWWWWWWWWWWWWWWWWW</td>
</tr>
</table>
Output of开发者_开发知识库 this will be as i want:
|Hello |WWWWWWWWWWWWWWWWWWWWWW|
But this solution does not wraps elements inside (in this case tds) to new line if it does not fit to screen width! So i would like to do this using divs and css. If i use:
<style>
#eq > div {
width: 400px;
float: left;
}
</style>
<div id="eq">
<div>Hello</div>
<div>WWWWWWWWWWWWWWWWWWWWWW</div>
</div>
Sure it works and outputs same, but of course text and number of elements inside #eq are variable! So if text "WWWWWWWWWWWWWWWWWWWWWW" will be changed to "lol", elements will be absurdly wide. On the other side, if i change it to longer text then defined width, width of all other smaller elements will be smaller. So final question is: How can i make width of all elements be as wide as widest element with ability to wrap using pure html & css and without manually specifying width?
Tables will be the easier option. Have you tried forcing wrap on table cells?
td {
word-wrap: break-word;
}
I don't think there is a pure CSS/HTML solution to your DIV
idea.
A little late to the party, to be sure, but I've posted a JSFiddle of a solution that's worked very well for me, with or without Javascript:
http://jsfiddle.net/jpgringo/LTEsZ/7/
HTML:
foobar
Wampeter, Foma, Granfalloons
"O Oysters, come and walk with us!"
The Walrus did beseech.
"A pleasant walk, a pleasant talk,
Along the briny beach:
We cannot do with more than four,
To give a hand to each."
=========================================
CSS:
body {
font-family:Verdana, Arial, sans-serif;
font-size:10px;
}
#myContentSection {
display:table;
width:100%;
}
#myContentSection .content {
display:table-row;
}
#myContentSection .subsection {
display:table-cell;
border:solid 1px gray;
/* the next line is optional, but gives equal-width columns if you know the
number of columns ahead of time */
width:33%;
padding:4px 8px;
}
========================================
(optional) JS:
var sectionID = 'myContentSection';
var subsectionClass = 'subsection';
var contentSection = document.getElementById(sectionID);
var colCount = contentSection.getElementsByClassName('subsection').length;
console.log('# of columns:', colCount);
var width = Math.floor(100/colCount);
console.log('column width: ', width,'%');
var css = '#' + sectionID + ' .' + subsectionClass + ' { width: ' + width + '%; }';
var style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.head.appendChild(style);
精彩评论