紧接上一篇。
如果要居中的是一个块元素呢。
1)如果你知道这个块元素的高度:
1 <main> 2 3 <div> 4 I'm a block-level element with a fixed height,centered vertically within my parent. 5 </div> 6 7 </main> 8 9 10 body { 11 background: #f06d06; 12 font-size: 80%; 13 } 14 15 main { 16 white; 17 height: 300px; 18 margin: 20px; 19 width:20 position: relative; 21 resize: vertical; 22 overflow: auto; 23 } 24 25 main div { 26 absolute; 27 top: 50%; 28 left:29 right:30 100px; 31 margin-top: -70px; 32 black; 33 color:34 padding:35 }
resize 属性规定是否可由用户调整元素的尺寸。resize: none|both|horizontal|vertical;
总结起来就是
1 .parent { 2 3 } 4 .child { 5 6 7 8 -50px; /* account for padding and border if not using box-sizing: border-box; */ 9 }
2)如果你不知道这个块元素的高度,因为他会变化的,比如图片变了,宽度变了,样式变了等等都会改变元素的高度。
2 3 4 } 5 6 7 8 9 10 13 14 } 15 16 23 24 transform: translateY(-50%); 25 27 }
总结起来就是要这样子:
8 }
3)当然,如果你可以使用flex
main { background: white; height: 300px; width: 200px; padding: 20px; margin: display: flex; flex-direction: column; justify-content: center; resize: vertical; overflow: auto; } main div { black; color: auto; }
总结起来就是
display: flex; 3 flex-direction: column; 4 justify-content: center; 5 }
下面我们就要进入我们的难点了,就是如何水平垂直方向都达到居中。
一般情况下,我们可以结合上面的方法来达到目标。但是总有一些意外发生。
1)元素是固定的大小。首先你得设置外边距为负值,上边距为高度的一般,左边距为宽度的一般,其次在采用固定在50%/50%(上左或者下右)就可以了。
position: relative; 60%; 0 auto; both; 100px; -70px 0 0 -120px; absolute; top: 50%; left: 20px; }
HTML代码和原来的一样,就不多说了。
总结起来就是:
.parent { relative; } .child { position: margin: -70px 0 0 -170px; }
2)不知道元素的大小。这是你可以利用transform的属性。使其在两个方向上都进行翻转-50%。这是基于当前元素的大小来进行剧中的。
transform: translate(-50%,-50%); auto; }
总结:
.child {View Code
3)如果你可以使用flexbox;
align-items: auto; }
总结起来就是:
center;
}
总结
如果以上方法你都掌握了,居中对你而言就是一个小问题。