根據螢幕尺寸使用 CSS 更改列寬
要根據螢幕尺寸更改列寬,請使用媒體查詢。媒體查詢適用於需要為平板電腦、手機、電腦等不同裝置設定樣式的情況。
首先,設定 div -
<div class="sample">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quod, maiores!</div>
設定初始寬度
要設定上述 div 的寬度,請在 CSS 中使用 width 屬性 -
.sample { width: 50%; background-color: lightblue; height: 200px; font-size: 18px; }
更改列寬
現在,要根據螢幕尺寸更改列寬,請將 width 設定為 100% -
.sample { width: 100%; }
螢幕尺寸小於 700 畫素時,寬度為 100% -
@media only screen and (max-width: 700px) { body { margin: 0; padding: 0; } .sample { width: 100%; } }
示例
以下程式碼可根據螢幕尺寸更改列寬 -
<!DOCTYPE html> <html> <head> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .sample { width: 50%; background-color: lightblue; height: 200px; font-size: 18px; } @media only screen and (max-width: 700px) { body { margin: 0; padding: 0; } .sample { width: 100%; } } </style> </head> <body> <h1>Changing column width based on screen size</h1> <div class="sample">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quod, maiores!</div> <p>Resize the browser window to 700px and below to see the above div width change to 100%</p> </body> </html>
廣告