重置 CSS 設定 (CSS Reset)
瀏覽器通常有自己的預設樣式,例如標題大小、段落間距等,這些預設樣式會導致不同瀏覽器間的顯示不一致。因此,我們通常會使用「CSS Reset」來重置這些樣式,然後根據自己的需求來設定樣式。
(1) 最常見的 CSS Reset
Eric Meyer 的 CSS Reset 是最廣泛使用的範本之一:
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
(2) Normalize.css
除了重置樣式,還有一種叫 Normalize.css 的工具,它不會完全重置樣式,而是讓不同瀏覽器之間的顯示保持一致,並且保留一些常見元素的樣式設置。
你可以在項目中通過 <link>
引入 Normalize.css,或直接將它下載到項目中使用:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css">
綜合範例
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="normalize.css"> <!-- 引入 Normalize.css -->
<link rel="stylesheet" href="styles.css">
<title>CSS Layout Example</title>
</head>
<body>
<div class="grid-container">
<div class="header">頁首</div>
<div class="menu">選單</div>
<div class="main">主內容</div>
<div class="footer">頁尾</div>
</div>
</body>
</html>
CSS:
.grid-container {
display: grid;
grid-template-areas:
"header header header"
"menu main main"
"footer footer footer";
grid-gap: 10px;
padding: 10px;
}
.header {
grid-area: header;
background-color: lightblue;
padding: 20px;
}
.menu {
grid-area: menu;
background-color: lightgray;
padding: 20px;
}
.main {
grid-area: main;
background-color: lightgreen;
padding: 20px;
}
.footer {
grid-area: footer;
background-color: lightcoral;
padding: 20px;
}
這個範例展示了如何通過 Grid 實現頁面布局,並使用 Normalize.css 來重置網頁樣式,確保不同瀏覽器之間顯示的一致性。