在 linkedin 上关注我
在 github.com 上关注我
点击阅读
没有boaring setion,我们可以重定向到编码!
flexbox 是一个强大的布局工具,可以轻松地将元素水平和垂直居中。
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>center div with flexbox</title><style> .container { display: flex; justify-content: center; /* horizontal center */ align-items: center; /* vertical center */ height: 100vh; /* full viewport height */ } .centered-div { width: 200px; height: 200px; background-color: lightblue; } </style><div class="container"> <div class="centered-div">centered with flexbox</div> </div>
css grid 是另一个强大的布局系统,可以轻松地将元素居中。
立即学习“前端免费学习笔记(深入)”;
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>center div with grid</title><style> .container { display: grid; place-items: center; /* center both horizontally and vertically */ height: 100vh; /* full viewport height */ } .centered-div { width: 200px; height: 200px; background-color: lightcoral; } </style><div class="container"> <div class="centered-div">centered with grid</div> </div>
此方法涉及绝对定位 div 并使用变换使其居中。
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>center div with absolute positioning</title><style> .container { position: relative; height: 100vh; /* full viewport height */ } .centered-div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 200px; height: 200px; background-color: lightgreen; } </style><div class="container"> <div class="centered-div">centered with absolute positioning</div> </div>
对指定宽度的元素设置 margin: auto 可以使其水平居中。
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>center div with margin auto</title><style> .container { width: 100%; height: 100vh; /* full viewport height */ display: flex; align-items: center; /* vertical center */ } .centered-div { margin: 0 auto; /* horizontal center */ width: 200px; height: 200px; background-color: lightcoral; } </style><div class="container"> <div class="centered-div">centered with margin auto</div> </div>
此方法使用 display: table 和 display: table-cell 来使元素居中。
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Center Div with Table Display</title><style> .container { display: table; width: 100%; height: 100vh; /* Full viewport height */ } .centered-div { display: table-cell; vertical-align: middle; /* Vertical center */ text-align: center; /* Horizontal center */ } .inner-div { display: inline-block; width: 200px; height: 200px; background-color: lightpink; } </style><div class="container"> <div class="centered-div"> <div class="inner-div">Centered with Table Display</div> </div> </div>
拜伊
快乐编码!