CSS 水平居中 | 您所在的位置:网站首页 › div设置文字居中 › CSS 水平居中 |
1.若元素内容为文字时,元素设置text-align:center (text-align属性指定元素文本的水平对齐方式。center:把文本排列到中间。) 菜鸟教程(runoob.com) p { text-align:center; background:red }这里是文本内容 2.父子元素宽度固定,父元素设置text-align:center ,子元素设置display:inline-block,并且子元素不能设置浮动,否则居中失效 .outer{ width:200px; height:150px; text-align:center; background:red } .inner { width:150px; height:40px; background:green; display:inline-block } 这里是子元素3.子父元素宽度固定,子元素设置 margin:auto,并且子元素不能设置 浮动,否则居中失效 水平居中原理:子元素若不设置宽度,则宽度将会覆盖父元素,margin:auto平分两侧空间 .outer{ background:red; width:150px; height:150px; } .inner { background:green; width:120px; height:120px; margin:auto } 这里是子元素4.子元素相对于父元素绝对定位,子元素上下左右全为 0,然后设置子元素 margin:auto 居中原理:margin:auto平分两侧空间 .outer{ background:red; width:200px; height:200px; position:relative; } .inner { position:absolute; background:green; width:150px; height:150px; top:0; right:0; bottom:0; left:0; margin:auto; } 这里是子元素 5.子元素相对定位,子元素 top,left 值为 50%,transform:translate(-50%,-50%); 居中原理:top/left:50%即子元素的上/左外边距边界与其包含块(即父元素)上/左边界之间偏移50%(如果 "position" 属性的值为 "static",那么设置 "top/left" 属性不会产生任何效果。),此刻子元素左上角位于以父元素左上角为原点的中心位置,translate(-50%,-50%)让子元素向左上移动自身宽高的50%,此时子元素相对父元素水平垂直居中。 .outer{ background:red; width:200px; height:200px; position:relative; } .inner { position:absolute; background:green; width:100px; height:100px; top:50%; left:50%; transform:translate(-50%,-50%); } 这里是子元素3 6.父元素设置 display:table-cell vertical-align:middle,子元素设置 margin:auto .outer{ background:red; width:150px; height:150px; display:table-cell; vertical-align:middle } .inner { background:green; width:120px; height:120px; margin:auto } 这里是子元素7.margin:0 auto;+text-align: center;(父元素需要设置宽、高) Ps:margin:0 auto;上下外边距为0px,左右外边距由浏览器计算(左右一样宽)。text-align属性指定元素文本的水平对齐方式,center:把文本排列到中间。 |
今日新闻 |
推荐新闻 |
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 |