@xunuo
2021-06-21T02:55:51.000000Z
字数 1471
阅读 1910
前端
水平居中:
垂直居中:
先将div的祖先元素的width和height设置为100%(默认为0的)清除margin和padding的浏览器默认样式。
html,body{width: 100%;height: 100%;top: 0px;left: 0px;}
设置div的垂直偏移top为50%,定位方式为relative,另外 因为偏移是整个div的,即div的顶部刚好处于浏览器中间,因此需要使其margin-top为-(div高度/2)
div{border: 1px solid #000000;width: 300px;height: 50px;margin: 0 auto;top: 50%;position: relative;margin-top: -50px;}
设置line-height与div高度相同可使div内文字垂直居中(直接<div>文字文字文字</div>)
div {border: 1px solid #000000;width: 500px;height: 100px;top: 50%;margin: 0 auto;position: relative;margin-top: -50px;/*文字设置*/font-size: 36px;text-align: center;line-height: 100px;}
方法一:父元素设置display:flex;
子元素设置margin:auto;
具体代码实现如下:
<div class="flex-container"><div class="flex-item"></div></div><style>.flex-container {display:flex;width:500px;height:500px;background:lightgray;}.flex-item {margin:auto;width:200px;height:200px;background:darkred;}</style>
方法二:父元素设置display:flex;
然后再通过弹性盒子属性设置水平和垂直居中:
水平居中:align-items:center;
垂直居中:justify-content:center;
具体实现代码如下:
<div class="parentDiv"><div class="childDiv">这是一段文字</div></div><style>/**这里是设置parentDiv相对于整个页面居中:*/html,body{width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;}/**这里是设置childDiv居中*/.parentDiv {width: 700px;height: 500px;display: flex;align-items: center;justify-content: center;border: 1px solid #FF0000;}/**childDiv的设置,在里面设置了文字居中*/.childDiv {border: 1px solid #000000;width: 500px;height: 100px;/*文字设置*/font-size: 36px;text-align: center;line-height: 100px;}</style>
