CSS(Cascading Style Sheets)是一种用来描述HTML或XML(包括SVG、MathML等各种XML方言)文档样式的样式表语言。通过CSS,可以控制网页的布局和外观。
style
属性。<head>
部分使用<style>
标签。<link>
标签引入外部CSS文件。CSS广泛应用于各种网页设计,包括但不限于:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Centered CSS</title>
<style>
.centered {
display: block;
margin-left: auto;
margin-right: auto;
width: 50%;
background-color: lightblue;
padding: 20px;
text-align: center;
}
</style>
</head>
<body>
<div class="centered">
This is centered horizontally.
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Centered CSS</title>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.centered {
background-color: lightblue;
padding: 20px;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<div class="centered">
This is centered both horizontally and vertically.
</div>
</div>
</body>
</html>
原因:
解决方法:
margin-left: auto; margin-right: auto;
或display: flex; justify-content: center; align-items: center;
。通过以上方法,可以有效地将CSS内容居中显示在页面中间。
领取专属 10元无门槛券
手把手带您无忧上云