如何将块级元素水平居中?
CSS 中的 margin 属性可以用来水平居中块级元素,例如 div。我们可以设置元素的宽度,这样可以防止容器拉伸。块级元素占据整行空间,这会导致其他元素占据下一行,因为块级元素占据容器的 100%。
块级元素的水平居中
任何在网页上开始新行的元素都被认为是块级元素。例如,标题标签、div 等。
这些块级元素占据网页的全部宽度。假设我们在网页上有一个元素,它只占据网页的 10%,但如果它是块级元素,那么它将占据 100% 的宽度。
我们可以通过将 display 属性的值设置为 block 来更改任何特定元素的 display 属性。
语法
让我们看看 display 属性的语法:
display: value;
以上是 display 属性的语法,它可以用来定义网页上特定元素的外观。
margin 属性
现在我们知道了块级元素的行为,我们将使用 **margin** 属性来水平对齐元素。
margin 属性将控制块级元素的位置。我们将以一种使元素居中的方式使用该属性,因为 margin 可以控制元素在 **水平** 和 **垂直** 方向上的位置。
语法
让我们看看 margin 属性的语法:
margin: value;
这是 margin 属性的语法,应该从左右指定 margin,以便块级元素居中。auto 值可以用来设置 margin,以便块级元素可以自动居中。
**注意** - 有一个属性 text-align 和它的值 center。此属性不能用于此方法,因为它用于居中非块级元素,如段落、span 标签等。
示例
为了更好地理解该属性的功能,让我们来看一个示例,在这个示例中,我们添加了一些标题和一个 div,其 margin 在 CSS 属性部分设置为 auto,然后将它们与两个内联块一起居中。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 来对齐块级元素。
示例
在下面的程序中,我们将获取一个图像和一个紧随图像之后的非块级元素。然后我们将图像的 display 设置为 block,并将它的 margin 设置为 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://tutorialspoint.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 值,您可以快速轻松地对齐设计中的任意数量的元素。通过一些练习,您将能够自信地使用这些技巧!
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP