给已知大小的元素设置上下左右居中
产品经理:我这有一张200×200的图片,你帮我在浏览器上居中显示一下!
【方法1】定位后,上下左右的位置均设置0,最后设置margin为auto就可以啦!
.photo { width: 200px; height: 200px; position: fixed; top: 0; left: 0; right: 0; bottom: 0; margin: auto; }
【方法2】定位后,上和左的位置为50%,最后设置margin-top为负数高度的一半,margin-left为负数宽度的一半,也一样可以实现上下左右居中啦!
.photo { width: 200px; height: 200px; position: fixed; top: 50%; left: 50%; margin-top: -100px; margin-left: -100px; }
给未知大小的元素设置上下左右居中
产品经理:我这又有一张图片,然鹅我不知道大小,你还得帮我在浏览器上居中显示一下!
【方法1】无论你知不知道元素的宽高,都可以直接设置上和左的位置为50%,然后利用CSS3的属性transform使得元素向左偏移它自身的一半从而达到上下左右居中!
.photo { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); }
【方法2】让这个未知大小的元素相对于他的父元素水平垂直居中,只需要为父元素设置flex,再设置横轴及纵轴居中即可!(IE10版本及以下均不支持)
.photo-box { /* 在photo的父级元素中写入下方代码 */ display: flex; justify-content: center; align-items: center; }