31

我的 HTML 有问题。我在互联网上搜索过,但仍然没有真正的答案。

我有一个包含一些图片的网站,我希望它们位于中间。现在,在我的屏幕上,它们位于中间,但那是因为我通过将它们移到一侧来将它们放在那里。当我的朋友看它时,图像是偏离中心的。

这是网站;如果您在 13.5 英寸的屏幕上,它看起来会在中间。

4

4 回答 4

76

尝试这样的事情......

<div id="wrapper" style="width:100%; text-align:center">
<img id="yourimage"/>
</div>
于 2011-05-05T17:34:33.327 回答
32

文本对齐:居中

text-align:center样式应用于包含元素的元素将使这些元素居中。

<div id="method-one" style="text-align:center">
  CSS `text-align:center`
</div>

Thomas Shields 提到了这种方法



边距:0 自动

margin:0 auto样式应用于块元素将使其在其所在的元素中居中。

<div id="method-two" style="background-color:green">
  <div style="margin:0 auto;width:50%;background-color:lightblue">
    CSS `margin:0 auto` to have left and right margin set to center a block element within another element.
  </div>
</div>

user1468562 提到了这个方法


中心标签

我最初的回答是你可以使用<center></center>标签。为此,只需将您想要的内容放在标签之间居中即可。 不过,从 HTML4 开始,此标签已被弃用<center>今天仍然在技术上支持(9 年后更新此内容),但我推荐上面包含的 CSS 替代品。

<h3>Method 3</h1>
<div id="method-three">
  <center>Center tag (not recommended and deprecated in HTML4)</center>
</div>

您可以在这个 jsfiddle中看到这三个代码示例。

我决定我应该修改这个答案,因为我之前给出的答案已经过时了。当我建议将其作为解决方案时,它已经被弃用,这就是 9 年后现在避免使用它的更多理由。

于 2011-05-05T17:45:49.337 回答
9

在您的特定情况下,您可以将包含a元素设置为:

a {
    display: block;
    text-align: center;
}

JS Bin 演示

于 2011-05-05T17:42:21.783 回答
7
<div style='width:200px;margin:0 auto;> sometext or image tag</div>

这水平工作

于 2012-11-14T13:52:39.243 回答