问题
I have a div tag with a specific width that will receive a text through javascript.
<div id="titleTop" style="width:400px; height:25px; padding-top:15px;"></div>
And whenever the length of that text exceeds the width, the div should adjust its padding, so the 2nd line of the text isn't obscured by the other div positioned below.
if(document.getElementById("titleTop").innerHTML.length >= 70){
document.getElementById("titleTop").style.paddingTop = 5 + "px";
document.getElementById("titleTop").style.height = 35 + "px";
}
My problem is this method isn't very reliable. Is there any way to detect if the text triggered multiple lines inside the div? Or to have the padding adjust itself proportionately?
EDIT: Just to make things clear, my problem isn't with the height of the div (it has to stay 40px high at all times), but with aligning the text vertically within it
回答1:
.yourDivClass {
display: table-cell;
vertical-align: middle;
}
That should align your content. Finally, eliminate extraneous CSS and your JavaScript function to keep your code as simple as possible.
回答2:
To have a fixed height div with vertically centered text, remove the padding from your div, and use:
style="vertical-align:middle; display:table-cell;"
This will center the text vertically. No JavaScript will be needed any more.
回答3:
but with aligning the text vertically within it
If you want to vertically center align text inside a <div> of a specific height, set the CSS property line-height to the same value as the height property of the <div> (cross-browser).
回答4:
No need for JS. remove padding-top, set height and use vertical-align:middle; and display:table-cell;
here is a working fiddle
来源:https://stackoverflow.com/questions/13644930/how-to-detect-when-multiple-lines-are-occurring-in-a-div