如何使用CSS使具有液体宽度和高度的div的水平和垂直绝对中心水平?在此先感谢您的帮助。
#div_parent{
background:#ccc;
position:relative;
}
.div_child{
background-color:#338BC7;
position: absolute;
left: 50%;
width: auto;
height: auto;
padding: 20px;
top:25%;
background: blue;
color: white;
text-align: center;
border:1px solid #ccc;
}
<div id="div_parent">
<div class="div_child">
<p>Centered In The Middle Of The Page.</p>
</div>
</div>
您的代码有几个问题:
width
和上height
指定html
和body
,否则,任何后代元素都将没有引用以百分比单位设置其位置和/或尺寸。#div_parent
,否则就无法将其绝对定位的子项(相对于它的位置)定位到垂直中心。此外,当您要将您.div_child
放置在页面的中央时,为什么还要将父母包裹在页面上。除了解决上述问题外,通常用于水平和垂直对齐元素的技巧是transform: translate
将其向后移动50%
。
像这样:
.div_child {
position: absolute; left: 50%; top: 50%;
transform: translate(-50%, -50%);
...
}
小提琴:http : //jsfiddle.net/abhitalks/Lnqvqnkn/
片段:
* { box-sizing: border-box; paddin:0; margin: 0; }
html, body { height: 100%; width: 100%; }
#div_parent{ height: 100%; width: 100%; background: #ccc; position: relative;}
.div_child {
background-color: #338BC7;
position: absolute; left: 50%; top: 50%;
transform: translate(-50%, -50%);
width: auto; height: auto;
padding: 20px; color: white; text-align: center; border: 1px solid #ccc;
}
<div id="div_parent">
<div class="div_child">
<p>Centered In The Middle Of The Page.</p>
</div>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句