如何在 CSS 中将 div 水平居中

问题描述 投票:0回答:1

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 的水平居中吗?我将非常感谢任何帮助或见解。 `

javascript html css centering
1个回答
0
投票

要将 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>
© www.soinside.com 2019 - 2024. All rights reserved.