CSS 中元素的寬度和高度
要指定元素的高度和寬度,分別使用 CSS 的 height 和 width 屬性。我們還可以使用 max-height、max-width、min-height 和 min-width 屬性設定這些屬性的最大值和最小值。
語法
以下是 CSS 中 height 和 width 屬性的語法:
Selector { height: /*value*/ width: /*value*/ }
以下是 height 屬性的值:
auto − 高度由網頁瀏覽器計算
length − 高度以長度單位定義
% − 高度以百分比設定
以下是 width 屬性的值:
auto − 高度由網頁瀏覽器計算
length − 高度以長度單位定義
% − 高度以百分比設定
元素的實際寬度和高度計算如下:
盒子大小 |
計算方式 |
---|---|
總寬度 |
width + padding-left + padding-right + border-left + border-right + margin-left + margin-right |
總高度 |
height + padding-top + padding-bottom + border-top + border-bottom + margin-top + margin-bottom |
以下示例說明了 CSS height 和 CSS width 屬性:
div 的高度和寬度
此處使用 heigh 和 width 屬性設定 div 容器的高度和寬度:
#demo { margin: auto; width: 400px; height: 80px; border: 2px solid black; display: flex; border-radius: 15px; }
示例
讓我們看看這個例子:
<!DOCTYPE html> <html> <head> <style> #demo { margin: auto; width: 400px; height: 80px; border: 2px solid black; display: flex; border-radius: 15px; } #demo div { flex: 1; border: thin dotted; border-radius: 50%; line-height: 60px; text-align: center; } #orange { box-shadow: inset 0 0 8px orange; } #green { box-shadow: inset 0 0 8px green; } #blue { box-shadow: inset 0 0 8px blue; } #red { box-shadow: inset 0 0 8px red; } </style> </head> <body> <h1>Demo Heading</h1> <div id="demo"> <div id="orange">Somebody</div> <div id="green">that I</div> <div id="blue">used</div> <div id="red">to know</div> </div> </body> </html>
導航選單的高度和寬度
選單的高度和寬度使用 height 和 width 屬性設定:
nav { width: 100%; background-color: rgb(39, 39, 39); overflow: auto; height: auto; }
示例
讓我們看看這個例子:
<!DOCTYPE html> <html> <head> <title>HTML Document</title> <style> body { margin: 0px; margin-top: 10px; padding: 0px; } nav { width: 100%; background-color: rgb(39, 39, 39); overflow: auto; height: auto; } .links { display: inline-block; text-align: center; padding: 14px; color: rgb(178, 137, 253); text-decoration: none; font-size: 17px; } .links:hover { background-color: rgb(100, 100, 100); } input[type="text"] { float: right; padding: 6px; margin-top: 8px; margin-right: 8px; font-size: 17px; } .selected { background-color: rgb(0, 18, 43); } </style> </head> <body> <nav> <a class="links selected" href="#">Home</a> <a class="links" href="#">Login</a> <a class="links" href="#">Register</a> <a class="links" href="#">Contact Us </a> <a class="links" href="#">More Info</a> <input type="text" placeholder="Search Here.." /> </nav> </body> </html>
影像的高度和寬度
讓我們看一個使用 height 和 width 屬性設定影像的高度和寬度的示例。
img { border: 8px solid rgb(0, 238, 255); width: 400px; height: 400px; }
示例
這是示例:
<!DOCTYPE html> <html> <head> <style> img { border: 8px solid rgb(0, 238, 255); width: 400px; height: 400px; } </style> </head> <body> <h1>Border Around Image Example</h1> <img src="https://tutorialspoint.tw/scala/images/scala-mini-logo.jpg"> </body> </html>
廣告