CSS Vertical Align DIV to the Middle

时间:2023-01-07 03:58:20

I am trying to put a div element in the centre of a container div both horizontally and vertically when we don't know the height of the container.

当我们不知道容器的高度时,我试图在水平和垂直方向上将div元素放在容器div的中心。

I have set up the container element to fit the full height and width of the document by absolute positioning, but cannot get the vertical alignment.

我已经设置了容器元素,以通过绝对定位来适应文档的整个高度和宽度,但无法获得垂直对齐。

.ui .chv {
  text-align: center; 
  position: absolute; 
  top: 60px;
  bottom: 50px; 
  left: 20px;
  right: 20px; 
  display: block;
  margin: 0; 
  height: auto;
  background: green; 
  text-align: center;
  vertical-align: middle;
}

LIVE DEMO

1 个解决方案

#1


3  

vertical-align:middle will work if the div have display:table-cell style. Div with "display:table-cell" should have a parent div with display:table

如果div有显示,则vertical-align:middle将起作用:table-cell style。带“display:table-cell”的div应该有一个带有display:table的父div

Put following html inside<div class="chv"></div>

将以下html放在

<div class="table full-width full-height">        
            <div class="table-cell align-middle">
                TEST
            </div>
 </div> 

so the final markup will be like this

所以最终的标记将是这样的

<div align="center" class="ui">
    <div class="chv">

        <div class="table full-width full-height">        
            <div class="table-cell align-middle">
                TEST
            </div>
        </div>    

    </div>    
</div>​

See this in jsfiddle

在jsfiddle中看到这个

I added .full-width, .full-height classes to set width and height 100%.

我添加了.full-width,.full-height类来设置宽度和高度100%。

#1


3  

vertical-align:middle will work if the div have display:table-cell style. Div with "display:table-cell" should have a parent div with display:table

如果div有显示,则vertical-align:middle将起作用:table-cell style。带“display:table-cell”的div应该有一个带有display:table的父div

Put following html inside<div class="chv"></div>

将以下html放在

<div class="table full-width full-height">        
            <div class="table-cell align-middle">
                TEST
            </div>
 </div> 

so the final markup will be like this

所以最终的标记将是这样的

<div align="center" class="ui">
    <div class="chv">

        <div class="table full-width full-height">        
            <div class="table-cell align-middle">
                TEST
            </div>
        </div>    

    </div>    
</div>​

See this in jsfiddle

在jsfiddle中看到这个

I added .full-width, .full-height classes to set width and height 100%.

我添加了.full-width,.full-height类来设置宽度和高度100%。