如何将HTML元素居中显示:Flexbox和绝对定位两种方法
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'>
<title>WebCat</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.box {
width: 200px;
height: 200px;
background: rgba(0, 0, 0, 1);
}
</style>
</head>
<body>
<div class='box'></div>
</body>
</html>
<p>使用绝对定位:</p>
<pre><code class="language-html"><!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'>
<title>WebCat</title>
<style>
body {
position: relative;
height: 100vh;
margin: 0;
}
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background: rgba(0, 0, 0, 1);
}
</style>
</head>
<body>
<div class='box'></div>
</body>
</html>
</code></pre>
<p>这两种方法都可以将box居中显示在页面上。可以根据实际情况选择使用哪种方法。</p>
原文地址: https://www.cveoy.top/t/topic/qm5L 著作权归作者所有。请勿转载和采集!