HTML CSS 浏览器元素居中显示
作为后端程序员,假如只是偶尔使用一下html,布局什么的忘记的很快,这里总结了在 HTML 和 CSS 中实现居中显示元素的几种方法,包括了水平居中、垂直居中、水平垂直居中。通常针对不同的元素类型,选择合适的居中方式。
水平居中
a. 使用text-align: center;
(适用于行内元素):
<div style="text-align: center;">
<p>This is a centered text.</p>
</div>
b. 使用margin: 0 auto;
(适用于块级元素):
<div style="width: 200px; margin: 0 auto;">
<p>This is a centered block with a fixed width.</p>
</div>
c. 使用Flexbox(适用于容器内的子元素):
<div style="display: flex; justify-content: center;">
<p>This is a centered text using Flexbox.</p>
</div>
d. 使用Grid(适用于容器内的子元素):
<div style="display: grid; place-items: center;">
<p>This is a centered text using Grid.</p>
</div>
垂直居中
a. 使用Flexbox(适用于容器内的子元素):
<div style="background:red; display: flex; align-items: center; height: 200px;">
<p>This is a vertically centered text using Flexbox.</p>
</div>
b. 使用Grid(适用于容器内的子元素):
<div style="background:red; display: grid; place-items: center; height: 200px;">
<p>This is a vertically centered text using Grid.</p>
</div>
c. 使用绝对定位(适用于已知高度的元素):
<div style="background:red; position: relative; height: 200px;">
<p style="position: absolute; top: 50%; transform: translateY(-50%);">This is a vertically centered text using absolute positioning.</p>
</div>
水平垂直居中
a. 使用Flexbox:
<div style="background: red; display: flex; justify-content: center; align-items: center; height: 200px;">
<p>This is a horizontally and vertically centered text using Flexbox.</p>
</div>
b. 使用Grid:
<div style="background: red; display: grid; place-items: center; height: 200px;">
<p>This is a horizontally and vertically centered text using Grid.</p>
</div>
c. 使用绝对定位和transform:
<div style="background: red; position: relative; height: 200px;">
<p style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);">This is a horizontally and vertically centered text using absolute positioning and transform.</p>
</div>