【CSS】對於超出div部分的處理,css超出div
一個正常的前端攻城獅,一般情況不會把內容布置到div外面,但是如果這部分的內容,是使用者輸入的,然後是從資料庫中取出來的,那樣有內容超出div部分也是很正常的,尤其是這部分內容,是使用者通過編輯器編輯的,便有可能出現這樣的情況:
比如,限制一個寬350px,高100px的表格,使用者用編輯器設定了一個400px x 400px的表格,就會溢出。
<div style="border:2px solid #000000; width:350px; height:100px;"> <table border="0" cellpadding="0" cellspacing="0" width="400" height="400"> <tr> <td style="background-color:#ff0000; width:200px; height:200px;"></td><td style="background-color:#0000ff; width:200px; height:200px;"></td> </tr><tr> <td style="background-color:#0000ff; width:200px; height:200px;"></td><td style="background-color:#ff0000; width:200px; height:200px;"></td> </tr> </table> </div>
這一部分是單純的英文還好,直接利用《【CSS】div圖層邊界對英文換行控制的問題》(點擊開啟連結)解決就可以了。
問題這是不可以壓縮的表格!千萬不要以為網頁的表格還可以像Excel那樣自動調整列寬之類的……
此時你可以利用到overflow這個屬性。
對於上面這種情況,可以考慮在style中補上overflow: auto;,給這東西補上捲軸的方式來解決,我只找到這種方式了,如果有更好的解決方案歡迎交流,具體代碼如下:
<div style="overflow: auto; border:1px solid red; width:350px; height:100px;"> <table border="0" cellpadding="0" cellspacing="0" width="400" height="400"> <tr> <td style="background-color:#ff0000; width:200px; height:200px;"></td><td style="background-color:#0000ff; width:200px; height:200px;"></td> </tr><tr> <td style="background-color:#0000ff; width:200px; height:200px;"></td><td style="background-color:#ff0000; width:200px; height:200px;"></td> </tr> </table> </div>
效果如:
對於單行文字的話,如果要像上面一樣給其補...,一般常見於標題,可以使用如下的方式解決,利用的overflow:hidden屬性。再補上text-overflow:ellipsis;white-space:nowrap;兩個屬性即可,但注意這東西只對於單行文本有用,如果是多行文本,做好還以使用後端語言,在輸出前加個條件結構,根據長度是否加點點點再輸出。畢竟前端幫到你這裡了。
<div style="overflow:hidden;width:100px;text-overflow:ellipsis;white-space:nowrap; "></div>
最後貼上上面那個Gif的全部源碼。JavaScript的代碼非常簡單,1行完事。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>OverFlow</title> </head> <body> <div style="overflow: auto; border:1px solid red; width:350px; height:100px;"> <table border="0" cellpadding="0" cellspacing="0" width="400" height="400"> <tr> <td style="background-color:#ff0000; width:200px; height:200px;"></td><td style="background-color:#0000ff; width:200px; height:200px;"></td> </tr><tr> <td style="background-color:#0000ff; width:200px; height:200px;"></td><td style="background-color:#ff0000; width:200px; height:200px;"></td> </tr> </table> </div><div id="textOver" style="overflow:hidden;width:100px;text-overflow:ellipsis;white-space:nowrap; "></div><input id="textInput" type="text" /><button onclick="input()">確定</button> </body></html><script>function input(){document.getElementById("textOver").innerHTML=document.getElementById("textInput").value;}</script>