怎么使得body内的一个元素始终居中

图片描述

如图,想要实现不论外面的大盒子即浏览器怎样变化,其内的小盒子始终处在大盒子的正中间。试了一些办法如margin的auto啊,弹性盒模型的center啊,好像都不行。望各位大神指点,谢谢啦0.0

阅读 6.2k
6 个回答

<!DOCTYPE html>
<html>
<head>

<title></title>

</head>
<body>
<style type="text/css">

.box{
    width:100px;
    height: 100px;
    margin:0 auto;
    background: red;

}

</style>

    <div class="box"></div>

</body>
</html>

你把小盒子的width设置了,在margin: 0 auto

可以设置了小盒子宽度后 给小盒子定位 用transform

这个其实就是一个水平垂直居中的问题,用css有好多种实现方案的,position的定位,css3的flex。可以参考一下我之前写的这篇水平垂直居中笔记

查一下资料就好了

 .box{
    width: 400px;
    height: 400px;
    background-color: #e5e5e5;
    position: relative;
}
.pox{
    width: 100px;
    height: 100px;
    background-color: #000;
    margin: auto;  
    position: absolute;  
    top: 0; left: 0; bottom: 0; right: 0;  
}
//或者
.pox{
    width: 100px;
    height: 100px;
    position: absolute;  
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%); 
}
<div class="box">
       <div class="pox"></div>
</div>
推荐问题