在水平和垂直方向居中一个div,并在调整父项大小时保持居中 [英] Center a div horizontally and vertically and keep centered when resizing the parent
问题描述
我可以减少/增加窗口的宽度,而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>
< 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:
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屋!