如何在我的叠加div中垂直居中?

时间:2017-05-09 07:09:43

标签: html css twitter-bootstrap reactjs typescript

我使用的是Typescript,React.js和Bootstrap 3。

我有一个叠加div,当我从服务器加载数据时,我将其置于详细内容的顶部。

在叠加层中,我有一个动画微调器,实现为span / glyphicon。

在以下代码中,textAlign有效,但verticalAlign没有。

任何人都可以说明这有什么问题 - 我需要做些什么来使微调器垂直和水平居中?

let loadingOverlay = <div style={{
  position: 'absolute',
  opacity: 0.7,
  width: '100%',
  height: '100%',
  color: 'white',
  backgroundColor: 'DarkGrey',
  zIndex: 1,
  border: 0, padding: 0, margin: 0,
  textAlign: 'center',
  verticalAlign: 'middle',

}}>
  <span 
    className="glyphicon glyphicon-refresh"
    style={{
      fontSize: 50,
      animation: 'spin 1s infinite linear'
    }}
  />
</div>;

let detailPanel = <div className="well" style={{margin: 2, padding: 5}}>
  <div style={{position: 'relative'}}>
    {workingStatus && loadingOverlay}
    {detailForm}
  </div>
  ...
</div>;

2 个答案:

答案 0 :(得分:2)

您可以将flexbox用于此

let loadingOverlay = <div style={{
  position: 'absolute',
  opacity: 0.7,
  width: '100%',
  height: '100%',
  color: 'white',
  backgroundColor: 'DarkGrey',
  zIndex: 1,
  border: 0, padding: 0, margin: 0,
  textAlign: 'center',
  verticalAlign: 'middle',
  display:flex;
  align-items: center;
  justify-content: center;

}}>
  <span 
    className="glyphicon glyphicon-refresh"
    style={{
      fontSize: 50,
      animation: 'spin 1s infinite linear'
    }}
  />
</div>;

let detailPanel = <div className="well" style={{margin: 2, padding: 5}}>
  <div style={{position: 'relative'}}>
    {workingStatus && loadingOverlay}
    {detailForm}
  </div>
  ...
</div>;

答案 1 :(得分:1)

您可以使用top: 50%transform: translateY(-50%)将图标垂直居中。像这样:

let loadingOverlay = <div style={{
  position: 'absolute',
  opacity: 0.7,
  width: '100%',
  height: '100%',
  color: 'white',
  backgroundColor: 'DarkGrey',
  zIndex: 1,
  border: 0, padding: 0, margin: 0,
  textAlign: 'center',

}}>
  <span 
    className="glyphicon glyphicon-refresh"
    style={{
      fontSize: 50,
      animation: 'spin 1s infinite linear',
      top: '50%',
      transform: 'translateY(-50%)'
    }}
  />
</div>;

let detailPanel = <div className="well" style={{margin: 2, padding: 5}}>
  <div style={{position: 'relative'}}>
    {workingStatus && loadingOverlay}
    {detailForm}
  </div>
  ...
</div>;

您可以在下面看到一个有效的HTML演示。我删除了内联样式并添加了id以便于阅读:

&#13;
&#13;
#outer {
  position: relative;
  height: 200px;  /*added for demo*/
}

#inner {
  position: absolute;
  opacity: 0.7;
  width: 100%;
  height: 100%;
  color: white;
  background-color: DarkGrey;
  z-index: 1;
  border: 0;
  padding: 0;
  margin: 0;
  text-align: center;
}

#inner span {
  font-size: 50;
  animation: spin 1s infinite linear;
  top:50%;
  transform: translateY(-50%);
}
&#13;
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>

<div id="outer">
  <div id="inner">
    <span class="glyphicon glyphicon-refresh"></span>
  </div>
</div>
&#13;
&#13;
&#13;