在 HTML 和 CSS 中将元素居中

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

我目前正在从事一个 Web 开发项目,并面临使用 CSS 将 HTML 元素或图像置于容器中居中的挑战。尽管尝试了多种方法,但我似乎无法实现所需的对齐。

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
  <div class="container">
    <img src="example.jpg" alt="Center Me">
  </div>
</body>
</html>

我尝试放入 html 元素

text-align:center;
我尝试过使用 text-align: center、margin: auto、flexbox 和 grid 等技术,但它们都没有按预期工作。该元素仍然偏离中心,我正在努力找出问题所在。 我创建了一个最小的示例来说明该问题,但我不确定我的 CSS 代码中缺少什么。如果有任何使用 CSS 将元素或图像居中于容器内的指导或替代方法,我将不胜感激。

javascript html css alignment center
1个回答
0
投票

要将图像在网页上居中,您可以使用 CSS 来设置图像及其容器的样式。以下是修改 HTML 和 CSS 以使图像居中的方法:

body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh; /* This ensures the content takes up the full viewport height */
            margin: 0; /* Remove default margin to prevent unwanted space */
        }

        img {
            max-width: 100%; /* Make sure the image doesn't exceed its container width */
        }
© www.soinside.com 2019 - 2024. All rights reserved.