html - 如何水平居中元素?

标签 html css alignment centering

如何水平居中 <div>在另一个<div>使用 CSS?

<div id="outer">
  <div id="inner">Foo foo</div>
</div>

最佳答案

flexbox水平和垂直居中设置 div 的样式非常容易。

#inner {  
  border: 0.05em solid black;
}

#outer {
  border: 0.05em solid red;
  width:100%;
  display: flex;
  justify-content: center;
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>

要使 div 垂直居中对齐,请使用属性 align-items: center .


其他解决方案

您可以将此 CSS 应用于内部 <div> :

#inner {
  width: 50%;
  margin: 0 auto;
}

当然,您不必设置 width50% .小于包含 <div> 的任何宽度将工作。 margin: 0 auto什么是实际居中。

如果您的目标是 Internet Explorer 8 (及以后),最好改用这个:

#inner {
  display: table;
  margin: 0 auto;
}

它将使内部元素水平居中,并且无需设置特定的 width 即可工作。 .

这里的工作示例:

#inner {
  display: table;
  margin: 0 auto;
  border: 1px solid black;
}

#outer {
  border: 1px solid red;
  width:100%
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>

关于html - 如何水平居中元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58048732/

相关文章:

html - 尝试居中对齐图像

html - 如何让带有/标题的图像保持在一行/同一行?

ios - 仅更改默认 backBarButtonItem 的位置

javascript - 通过 AJAX 使用 $().each 将innerHTML分配给元素不起作用

javascript - 在动态输入字段中显示多行

python - 复制 html 代码从 "string"到下一个 "string"

html - 闪耀在 Logo 上的闪屏

html - CSS 布局方法 : Rounded Corner not CSS3 & images along sides (not just corners)

html - 向 flex 元素添加滚动

javascript - 找不到解决方案 : load images to div based on page location