使用css将页面中间的div框居中

X10*_*0nD 7 css

我想在页面中间右侧居中一个div,我试过了top:30%,但是当窗口调整到对齐时.

<div id=cent></div>
Run Code Online (Sandbox Code Playgroud)

谢谢让

nai*_*sts 16

如果您知道该div的高度/宽度(例如,它将是100px X 200px),那么您可以这样做:

#cent {
  position:absolute;
  top:50%;
  left:50%;
  margin-top:-50px; /* this is half the height of your div*/  
  margin-left:-100px; /*this is half of width of your div*/
}
Run Code Online (Sandbox Code Playgroud)

更新:另一种选择:见http://www.w3.org/Style/Examples/007/center(垂直居中)


ale*_*hao 8

我知道这个问题很老了,但我偶然发现了它,我将来可能会再次寻找它。

就我而言,内容的高度可变,并且我不想使用绝对定位,因此我使用了 Flexbox 容器。您只需使用以下样式将内容包装在 div 中:

.container {
  min-height: 100vh; /* minimum height = screen height */
  display: flex;
  justify-content: center;
  align-items: center;
}
Run Code Online (Sandbox Code Playgroud)

示例: https: //codepen.io/alephao/pen/mdPRYqZ


Spi*_*idE 0

 <div id="content"
                 style="text-align: center;
                 vertical-align: middle;
                 border-color: #000000;
                 border-width: 1px;
                 border-style: solid;
                 margin-top: 25%;
                 margin-bottom: 25%;">
                hi
            </div>
Run Code Online (Sandbox Code Playgroud)

这对我有用......

编辑:这将对齐整个 div...无论 div 或页面的大小...假设该 id 是整个页面中唯一的 div...