【问题标题】:How to center a div with a relative width?如何使具有相对宽度的 div 居中?
【发布时间】:2013-10-09 06:44:48
【问题描述】:

我有一个<div>,其样式如下:

.content{
    width: 70%;
}

要使 div 居中,可以将边距设置为自动 (margin: 0 auto;),但这仅在我有固定大小(例如 400 像素)时才有效。那么如何让我的 div 以相对宽度居中呢?

【问题讨论】:

  • 它应该可以工作.. 你有没有尝试添加“margin: 0 auto;”以及以 %?? 为单位的宽度
  • text-align: center 仅将div中的文本居中,而不是div itsel
  • 无需使用 text-align-center... "margin: 0 auto;"本身应该工作..
  • 检查是否有任何 CSS 规则覆盖边距或宽度设置,同时检查浮动。
  • 如果它不起作用,请添加您的代码或创建您的代码的小提琴..

标签: css html width margin


【解决方案1】:

margin: 0 auto 也适用于百分比 div。边距将根据宽度的百分比计算。

http://jsfiddle.net/B32mh/

【讨论】:

  • 嗯,这很烦人,它仍然不起作用,我还检查了我的 html 代码是否缺少标签或类似的东西,但一切都很好
  • 对不起,我的 div 没问题,我的背景和 hr 放错了位置
【解决方案2】:

使用

<body>
  <div class="content">
    <div class="centered"><h1>Hello</h1></div>
  </div>
</body>

和 CSS

.content {
  width: 70%;
  background-color: #e5e5e5;
}

.centered {
  width: 150px;
  background-color: #ccc;
  margin: 0 auto;
}

你明白了:

JsBin 上的演示:http://jsbin.com/iDAZeSi/1/


根据答案编辑

只需将margin: 0 auto; 添加到.content 就可以了

.content {
  width: 70%;
  background-color: #e5e5e5;
  margin: 0 auto;
}

你会得到:

JsBin 上的演示:http://jsbin.com/iDAZeSi/2/

【讨论】:

  • 我想使外部 div 居中,而不是其内容
  • 那么它是完全一样的,无论相对宽度与否,它仍然是一个有效的宽度,对于这样的margin: 0 auto; 有效!
【解决方案3】:

margin: 0 auto 也可以 或者您可以在内容 div 上使用 display: inline-block 并使用 text-align: center 将其包裹在 div 中

<div id="one">one</div>
<br /><br />
<div id="wrap">
    <div id="two">two</div>
</div>

CSS

#one {
    width: 70%;
    height: 100px;
    background: #ccc;
    margin: 0 auto;
    text-align: center;
}

#wrap { text-align: center; }
#two {
    width: 70%;
    height: 100px;
    background: #ccc;
    display: inline-block;
    text-align: center;

}

http://jsfiddle.net/4KhJL/3/

【讨论】:

    猜你喜欢
    • 2012-03-24
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-17
    • 2014-12-06
    • 2017-05-26
    • 1970-01-01
    相关资源
    最近更新 更多