屏幕中间居中div [重复]

问题描述 投票:38回答:5

在屏幕中央对齐语义ui网格的最佳模式是什么?

为此的CSS将是理想的。

.div{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
    width: 100px;
    height: 100px;
}

但是在语义上,这在网格中看起来不太好。

这是我的html的一部分。

 <div class="ui grid container">
    <div class="ui center aligned three column grid">
      <div class="column">
      </div>
      <div class="column">
        </div>
      </div>
  </div>
css semantic-ui
5个回答
73
投票

这应该适用于任何div或屏幕尺寸:

.center-screen {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  min-height: 100vh;
}
 <html>
 <head>
 </head>
 <body>
 <div class="center-screen">
 I'm in the center
 </div>
 </body>
 </html>

查看有关flex here的更多详细信息。这在大多数浏览器上都可以使用,请参见兼容性列表here

更新:如果不需要滚动条,请减小min-height的大小,例如min-height: 95vh;


23
投票

2018:CSS3

div{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%);
}

这更短。有关更多信息,请参见:CSS: Centering Things


22
投票

将div沿水平和垂直方向居中对齐的最佳方法是

HTML

<div></div>

CSS

div {
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    width: 100px;
    height: 100px;
    background-color: blue;
}

FIDDLE


1
投票

尝试一下:

 div{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
    width: 100px;
    height: 100px;
    background: red;
}

这里div是html标记。您写了一个html标记,后接一个错误的点。只写了一个类,后接了点。


0
投票

您的代码正确,您只使用了.div而不是div

HTML

<div class="ui grid container">
<div class="ui center aligned three column grid">
  <div class="column">
  </div>
  <div class="column">
    </div>
  </div>

CSS

div{
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
}

检查此Fiddle] >>

© www.soinside.com 2019 - 2024. All rights reserved.