CSS提供了居中的HTML元素。通过使用CSS,HTML元素可以有不同的布局。在本教程中,我们将学习如何使用CSS将HTML的文本、图像、文本块元素置于中心。
文本居中线
CSS提供 text-align
属性,用于设置文本元素的对齐方式。 center
可以向该属性提供值,以使文本元素居中,如下所示。在本例中,我们将集中文本元素,如 h2
和 p
.
Caption
This is a centered text
This is a centered text
This is a centered text
This is a centered text
This is a centered text
This is a centered text
This is a centered text

使文本或图像块居中
在某些情况下,我们可能需要中心不仅是给定的文本或字母,完全的文本块。我们可以使用 margin-left
和 margin-right
通过指定块的宽度来指定属性。在本例中,我们将把margin left和margin right属性设置为auto,并将width设置为12em,这将设置文本块的正文大小。
Caption
This is a centered text.This is a centered text.This is a centered text.This is a centered text.This is a centered text.This is a centered text.This is a centered text.This is a centered text.This is a centered text.This is a centered text.This is a centered text.This is a centered text.This is a centered text.This is a centered text.This is a centered text.This is a centered text.This is a centered text.This is a centered text.This is a centered text.This is a centered text.This is a centered text.This is a centered text.This is a centered text.This is a centered text.v

使块或图像垂直居中
到目前为止,我们已经将给定的文本或图像元素水平居中,但我们也可以使用 vertical-align
CSS属性。在本例中,我们将通过提供 middle
作为垂直对齐属性的值。
This small paragraph...
使图像居中
我们也可以使用 margin-left
和 margin-right
CSS属性。我们将提供 auto
作为左边距和右边距的值。
Center an Image
This text is normal text where there is no specific alingment about it.

使用填充垂直居中
我们可以使用 padding
属性以使给定的文本或图像垂直居中。
Center Vertically
We can use the padding property in order to center vertically
I am vertically centered.

垂直和水平居中
我们还可以将给定的文本或图像垂直和水平居中。我们将使用 line-height
和 vertical-align
具有不同值的属性。
Centering
We can also center the given text or image vertically and horizontally. We will use line-heigh and vertical-align attributes with different values
I am vertically and horizontally centered.
