如何在 HTML 中使 div 居中对齐?
htmlweb developmentfront end technology更新于 2025/12/7 6:07:17
DIV 被称为分隔标签,顾名思义,它用于对网页内容进行划分。
DIV 标签由打开和关闭标签
通过使用 class 或 id 属性,DIV 标签可以使用 CSS 轻松设置样式,也可以使用 JavaScript 进行操作。任何类型的数据都可以放置在
示例
以下是
p {
font-size: 15px;
margin: 8px;
}
div {
color: black;
margin: 4px;
font-size: 15px;
}
HTML tutorial
执行上述程序后,将显示一个包含 div 元素和文本的网页,文本颜色将按指定颜色显示为黑色。
HTML 中的 DIV 居中对齐
以下是 DIV 居中对齐 − 的用法
要将 div 元素居中对齐,我们使用 −
"div style="text-align:center" "
要将 div 居中,我们可以使用如下所示的语法 −
"div style="margin: 0 auto" "
示例
以下是
p {
font-size: 15px;
margin: 8px;
}
div {
color: black;
margin: 4px;
font-size: 15px;
}
Welcome to TutorialsPoint
执行上述程序后,将显示一个 div 元素及其内部的
元素,并在代码中显示指定的文本。
现在让我们看看居中 DIV 的不同对齐方式
使用 CSS Margin Auto 居中 DIV
使用值 0 auto 的 简写 margin 属性 将块级元素(如 div)水平居中 −
示例
以下是使用 CSS Margin Auto 居中对齐
.container {
font-family: arial;
font-size: 14px;
margin: 25px;
width: 350px;
height: 200px;
outline: dashed 1px black;
}
.child {
width: 50px;
height: 50px;
background-color: blue;
/* Center horizontally*/
margin: 0 auto;
}
Center a Div with CSS Margin Auto
运行上述程序时,将显示一个 div 元素,该元素的格式设置为居中,并使用 CSS 自动边距。
将 DIV 垂直和水平居中
要将 DIV 垂直和水平居中,我们需要知道要居中的元素的宽度和高度。
步骤
对于父元素,将position属性设置为relative。
将子元素的position属性设置为absolute,将top设置为50%,将left设置为50%。它使子元素的左上角垂直和水平居中。
应用设置为子元素高度一半的负上边距,以及设置为子元素宽度一半的负左边距。
示例
以下是
.container {
font-family: arial;
font-size: 14px;
margin: 25px;
width: 350px;
height: 200px;
outline: dashed 1px black;
position: relative;
}
.child {
width: 50px;
height: 50px;
background-color: green;
/* Center horizontally and vertically*/
margin: -25px 0 0 -25px ;
position: absolute;
top: 50%;
left: 50%;
}
Center Both Vertically and Horizontally
当我们运行上述程序时,将显示一个 div 元素和一个子 div 元素,其格式为居中。
相关文章
HTML DOM Input Number step 属性
HTML DOM Input Number placeholder 属性
HTML DOM Input Number required 属性
HTML DOM Select size 属性
HTML DOM Select value 属性
HTML DOM Select name 属性
HTML DOM Select multiple 属性
HTML DOM 进度对象
HTML DOM Option index 属性
HTML DOM Option disabled 属性
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.w3schools.cn/html/
打印
下一节 ❯❮ 上一节