提问人:Maria Graciela Esquivel Fernan 提问时间:9/13/2023 更新时间:9/13/2023 访问量:56
如何在CSS中将div水平居中[复制]
How can I center a div horizontally in CSS [duplicate]
问:
I'm currently working on a webpage, and one of the challenges I'm facing is centered horizontally a specific div on the screen. Despite my efforts, I haven't been able to achieve this as expected. Here's the HTML and CSS code I'm currently using:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="estilos.css">
</head>
<body>
<div class="mi-div">
<p>Contenido del div</p>
</div>
</body>
</html>
/* estilos.css */
.mi-div {
width: 300px;
/* this is the width*/
height: 200px;
/* this is the height*/
background-color: lightgray;
/* I assign is a background*/
/* Here's where I've attempted to center this div horizontally, but it hasn't worked so far. */
/* How can I center this div horizontally? */
}
I've explored various methods, including using
/* this is css code*/
margin: 0 auto;
and
/* this is css code*/
text-align: center;
',但它们似乎都没有达到预期的定心效果。
有人可以提供分步指南或替代方法来实现此 div 的水平居中吗?我将不胜感激任何帮助或见解。 `
答:
0赞
Shrey Soni
9/13/2023
#1
要使 div 居中,您可以查看以下代码:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="estilos.css">
<style>
body {
display: flex;
justify-content: center; /* Center the content horizontally */
align-items: center; /* Center the content vertically */
height: 100vh; /* Set the body's height to the viewport height for vertical centring */
}
</style>
</head>
<body>
<div class="mi-div">
<p>Contenido del div</p>
</div>
</body>
</html>
0赞
kigawas
9/13/2023
#2
目前,CSS布局通常由flexbox(一维,水平或垂直)或网格(二维)配置。你需要修改CSS,比如
.mi-div {
display: flex; /* specify flexbox */
align-items: center; /* center vertically */
justify-content: space-around; /* "simulate" centering horizontally */
width: 300px;
height: 200px;
background-color: lightgray;
}
.mi-div {
display: flex;
align-items: center;
justify-content: space-around;
width: 300px;
height: 200px;
background-color: lightgray;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="estilos.css">
</head>
<body>
<div class="mi-div">
<div>Contenido del div</div>
</div>
</body>
</html>
上一个:如何使水平导航列表在照片顶部居中
下一个:在每行 CSS 中居中屏幕特定列
评论