css
主页 > 网页 > css >

CSS设置水平垂直居中的7种方法总结

2024-03-25 | 佚名 | 点击:

1. 水平居中 - 文本或行内元素

使用 text-align 属性

1

2

3

.parent {

  text-align: center; /* 子元素如果是内联或内联块元素,将会水平居中 */

}

1

2

3

4

5

<!-- HTML -->

<div class="parent">

  <p>这是要居中的文本</p>

  <img src="image.jpg" alt="图片">

</div>

2. 水平居中 - 块级元素

使用 margin: 0 auto

1

2

3

4

.child {

  width: 300px; /* 需要给定一个宽度 */

  margin: 0 auto; /* 左右外边距自动分配 */

}

1

2

3

4

<!-- HTML -->

<div class="parent">

  <div class="child">这是要居中的块级元素</div>

</div>

3. 使用 Flexbox

1

2

3

4

.parent {

  display: flex;

  justify-content: center; /* 水平居中 */

}

1

2

3

4

<!-- HTML -->

<div class="parent">

  <div class="child">这是要居中的任何元素</div>

</div>

4. 垂直居中 - 单行文本

使用 line-height

1

2

3

4

5

6

.parent {

  height: 100px; /* 给定一个高度 */

}

.child {

  line-height: 100px; /* 与父元素高度相同 */

}

1

2

3

4

<!-- HTML -->

<div class="parent">

  <p class="child">这是单行垂直居中的文本</p>

</div>

5. 垂直居中 - 多行文本和块级元素

使用 Flexbox

1

2

3

4

5

.parent {

  display: flex;

  flex-direction: column;

  justify-content: center; /* 垂直居中 */

}

1

2

3

4

<!-- HTML -->

<div class="parent">

  <div class="child">这是多行垂直居中的内容</div>

</div>

6. 水平和垂直居中 - Flexbox 或 Grid

Flexbox 方式

1

2

3

4

5

.parent {

  display: flex;

  justify-content: center;

  align-items: center; /* 垂直居中 */

}

1

2

3

4

<!-- HTML -->

<div class="parent">

  <div class="child">水平和垂直居中</div>

</div>

Grid 方式

1

2

3

4

.parent {

  display: grid;

  place-items: center; /* 这相当于 align-items: center 和 justify-items: center 的简写 */

}

1

2

3

4

<!-- HTML -->

<div class="parent">

  <div class="child">使用Grid布局实现水平和垂直居中</div>

</div>

7. 使用 position 和 transform

当元素尺寸未知时,可以使用此方法。

1

2

3

4

5

6

7

8

9

.parent {

  position: relative;

}

???????.child {

  position: absolute;

  top: 50%;

  left: 50%;

  transform: translate(-50%, -50%);

}

1

2

3

4

<!-- HTML -->

<div class="parent">

  <div class="child">无论尺寸如何都会水平和垂直居中</div>

</div>

这些是CSS中最常用的居中方法,根据实际需求选择合适的策略。

原文链接:
相关文章
最新更新