如何将块元素居中对齐?
CSS 中的 margin 属性可用于将块元素(例如 div)水平居中。我们可以设置元素的宽度,以防止容器过度拉伸。块元素占据整行空间,由于块元素占据了容器的 100%,因此其他元素必须占据下一行。
将块元素居中对齐
网页上任何另起一行的元素都被视为块级元素。例如,标题标签、div 等。
这些块元素占据网页的整个宽度。假设我们的网页上有一个元素,它只占用网页宽度的 10%,但如果它是一个块元素,那么它将占用自身宽度的 100%。
我们可以通过设置 block 属性的值来更改任何特定元素的 display 属性。
语法
我们来看看 display 属性的语法 -
display: value;
以上是 display 属性的语法,该属性可用于定义网页上特定元素的外观。
margin 属性
现在我们了解了块元素的行为,我们将使用 margin 属性在水平面上对齐元素。
margin 属性将控制块元素的位置。我们将以某种方式使用该属性,使元素居中,因为外边距可以控制元素在水平和垂直平面上的对齐。
语法
让我们看看外边距属性的语法 -
margin: value;
以下是外边距属性的语法,外边距应从左右两侧指定,以使块元素居中。可以使用 auto 值设置外边距,使块元素自动与中心对齐。
注意 - 有一个属性 text-align 及其值 center。此属性无法用于此方法,因为它用于居中非块元素,例如段落、span 标签等。
示例
为了更好地理解此属性的功能,让我们看一个例子。在这个例子中,我们添加了一些标题和一个 div,其边距在 CSS 属性部分中设置为"自动",然后将它们与两个内联块元素一起居中。div 的不同颜色告诉我们不同的显示方式,例如内联块元素和其他元素。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of text alignment to the center</title>
<style>
*{
background-color:black;
}
.para {
color:white;
text-align: center;
}
.testinline {
padding: 10px;
border: 2px solid blue;
}
h1 {
font-size: 35px;
color: white;
width: fit-content;
margin: auto;
}
.container {
background-color: lightblue;
margin: auto;
border: solid red 1px;
padding: 15px 10px;
text-align: center;
width: fit-content;
}
.good-night {
padding: 10px;
border: 2px solid blue;
color: white;
display: inline-block;
}
.good-morning {
padding: 10px;
text-align: center;
color: white;
}
</style>
</head>
<body>
<h1>Hi, this an example</h1>
<p class="para">We are aligning the block elements to the text.</p>
<h1>Welcome</h1>
<div class="container">
How is your day Going
</div>
<div class="good-morning">
<div style="display: inline-block" class="testinline">
Good Morning
</div>
<div style="display: inline-block" class="testinline">
Good Night
</div>
</div>
</body>
</html>
在上面的输出中,您可以看到标题和 div 元素与段落标签一起居中排列。我们使用 text-align 属性将段落标签居中对齐,并使用 margin 属性并将其值设置为 auto 来对齐块元素。
示例
在下面的程序中,我们将使用一张图片以及一个位于图片旁边的非块元素。然后,我们将图片的显示设置为块,将其边距设置为 auto,然后将其与标题一起居中对齐,并将段落的 display 属性设置为 inline-block。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example for text alignment </title>
<style>
h1 {
margin: auto;
width: 30%;
font-size: 24px;
margin-bottom: 8px;
background-color: black;
color: white;
}
.image{
display: block;
margin: auto;
}
</style>
</head>
<body>
<h1>
Example for setting the block element
</h1>
<img class="image" src="https://www.cainiaomax.com/images/logo.png">
<p style="display: inline-block;">
Hi this is another example for aligning the block element to the centre.
</p>
</body>
</html>
在输出中,您可以看到图像位于中心,文本位于下一行,正如我们所希望的那样。
结论
将块元素居中对齐是创建平衡对称布局的绝佳方法。通过使用 text-align 或 margin auto 值,您可以快速轻松地对齐设计中的任意数量元素。经过一些练习,您将能够自信地使用这些技巧!
相关文章
有用资源
css 参考教程 - 该教程包含有关 css 的更多信息:https://www.cainiaomax.com/css/

