在水平和垂直方向居中一个div,并在调整父项大小时保持居中 [英] Center a div horizontally and vertically and keep centered when resizing the parent

查看:114
本文介绍了在水平和垂直方向居中一个div,并在调整父项大小时保持居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我可以减少/增加窗口的宽度,而div将始终保持为窗口中心

  .cent 
{
height:50px;
width:50px;
background-color:black;
margin:auto;
}

这里是 JSFiddle例子我目前的。
但是我想保持div垂直居中,如果我减少/增加窗口的高度,div将通过停留在窗口的中间响应。



对于这个例子,我想保持黑盒子垂直居中在窗口调整大小,方式与它始终居中在水平中心相同。

解决方案

您可以使用 CSS表格执行此操作:



strong> JsFiddle



标记

h2>

 < div class =container> 
< div class =cent>< / div>
< / div>



(相关)CSS



  html,body 
{
height:100%;
}
body
{
display:table;
margin:0 auto;
}

.container
{
height:100%;
display:table-cell;
vertical-align:middle;
}
.cent
{
height:50px;
width:50px;
background-color:black;
}


I want to center a div horizontally and vertically at all times.

I can reduce/increase the width of the window and the div will respond by always remaining in the center of the window

.cent
{
  height:50px;
  width:50px;
  background-color:black;
  margin:auto;
}

Here is a JSFiddle Example of what I have currently. But I want to keep the div centered vertically as well so if I reduce/increase the height of the window the the div will respond by staying in the middle of the window.

In regards to the example, I want to keep the blackbox vertically centered on window resize in the same way it always stays in the center horizontally.

解决方案

You can do this with CSS tables:

JsFiddle

Markup

<div class="container">
    <div class="cent"></div>
</div>

(Relevant) CSS

html,body
{
    height: 100%;
}
body
{
   display: table; 
   margin: 0 auto;
}

.container
{  
    height: 100%;
    display: table-cell;   
    vertical-align: middle;    
}
.cent
{
    height: 50px;
    width: 50px;
    background-color: black;      
}

这篇关于在水平和垂直方向居中一个div,并在调整父项大小时保持居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆