1. 居中元素
居中一个元素,无论是水平居中还是垂直居中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Centering Example</title>
<style>
.center-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.centered-element {
text-align: center;
}
</style>
</head>
<body>
<div class="center-container">
<div class="centered-element">
<h1>Centered Content</h1>
<p>This content is horizontally and vertically centered.</p>
</div>
</div>
</body>
</html>
2. 响应式导航栏
创建一个简单的响应式导航栏,适应不同屏幕尺寸。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Navbar Example</title>
<style>
body {
margin: 0;
font-family: Arial, sans-serif;
}
.navbar {
background-color: #333;
overflow: hidden;
}
.navbar a {
float: left;
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
.navbar a:hover {
background-color: #ddd;
color: black;
}
@media screen and (max-width: 600px) {
.navbar a {
float: none;
display: block;
text-align: left;
}
}
</style>
</head>
<body>
<div class="navbar">
<a href="#home">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
</div>
<div style="padding: 16px">
<p>This is some content.</p>
</div>
</body>
</html>
3. 卡片布局
创建一个简单的响应式卡片布局,适应不同屏幕尺寸。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Card Layout Example</title>
<style>
.card-container {
display: flex;
flex-wrap: wrap;
gap: 20px;
justify-content: space-around;
padding: 20px;
}
.card {
flex: 1 0 300px;
background-color: #f0f0f0;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
</style>
</head>
<body>
<div class="card-container">
<div class="card">
<h2>Card 1</h2>
<p>This is some content for card 1.</p>
</div>
<div class="card">
<h2>Card 2</h2>
<p>This is some content for card 2.</p>
</div>
<div class="card">
<h2>Card 3</h2>
<p>This is some content for card 3.</p>
</div>
</div>
</body>
</html>
这些例子覆盖了一些常见的CSS实战场景,包括居中元素、响应式导航栏和卡片布局。你可以使用这些例子作为起点,根据项目的需求进行修改和扩展。不断实践和尝试新的CSS技术是提高编程技能的有效途径。
转载请注明出处:http://www.zyzy.cn/article/detail/4031/CSS