【CSS】前端页面中常用的文字和区块元素的水平和垂直居中的设置方法 |
您所在的位置:网站首页 › 设置水平和垂直对齐方式均为居中 › 【CSS】前端页面中常用的文字和区块元素的水平和垂直居中的设置方法 |
为了让我们的页面能够更美观,很多时候我们都用到了水平和垂直居中的效果,下面笔者总结了常用的设置方法。 1.文字的居中对齐通常为单行文字在区块元素中设置水平和垂直居中: 设置text-align(文字对齐方式)为 center 使文字水平居中;设置line-height(字体行高)为区块元素的高度使文字垂直居中,因为设置的是字体行高所以该方法仅适用单行文字的垂直居中; div{ width: 100px; height: 30px; text-align: center; line-height: 30px; } 2.区块元素的居中对齐区块元素在其父元素中设置水平和垂直居中有多种,我们在body部分设置两个div 仅为块元素设置水平居中(1)为子元素设置左右外边距 #child{ margin: 0 auto; }(2)通过给子元素定位水平居中:将子元素向右移动父元素宽度的一半,再向左移动自身宽度的一半,达到水平居中的效果。 #child{ width: 150px; position: relative; left: 50%; margin: -75px; } /*这里的margin: -75px; 也可以用CSS3的位移函数来实现transform: translate(50%,0);*/注意:以上两种方法都能让子元素在其父元素中水平居中,自适应和定位都需要知道元素的宽度。 为块元素设置垂直和水平居中 我们还是使用上面两个div,下面是CSS部分:(1)实现方法一 #parent{ width: 500px; height: 300px; border: 1px solid red; background-color: #ccc; position: relation; } #child{ width: 300px; height: 200px; background-color: yellow; position: absolute; left: 50%; top: 50%; margin: -100px 0 0 -150px; }这里的margin: -100px 0 0 -150px;同样也可以用 transform: translate(-50%,-50%);来实现, 这样就不用知道子元素的宽高 #parent{ width: 500px; height: 300px; border: 1px solid red; background-color: #ccc; position: relation; } #child{ width: 300px; height: 200px; background-color: yellow; position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); }(2)实现方法二 #parent{ width: 500px; height: 300px; border: 1px solid red; background-color: #ccc; position: relation; } #child{ width: 300px; height: 200px; background-color: yellow; position: absolute; top: 0; right: 0; buttom: 0; left:0; margin: auto; }(2)实现方法三(flex布局) #parent{ width: 500px; height: 300px; border: 1px black solid; display: flex; justify-content: center; align-items: center; } #child{ width: 300px; height: 200px; background-color: pink; } |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |