请问可以用margin实现居中吗?我试了没有作用

请问可以用margin实现居中吗?我试了没有作用

<!DOCTYPE html>

<html>

<head>

  <meta charset="UTF-8">

  <title>Document</title>

  <style>

    /*完善下列代码*/

    .per{

     width: 300px;

     height: 300px;

     background: red;

     margin-left:200px;

     margin-top: 200px;

     position: relative;

   }


   .son{

     width: 100px;

     height: 100px;

     background: blue;

     position: absolute;

     left: 100px;

     top: 100px;

   }

  </style>

</head>

<body>

  <div class="per">

    <div class="son"></div>

  </div>

</body>

</html>


正在回答

登陆购买课程后可参与讨论,去登陆

1回答

在per里面设置 margin:200px auto 0;即可

.per{
     width: 300px;
     height: 300px;
     background: red;
     /*margin-left:200px;
     margin-top: 200px;*/
     margin:200px auto 0;
     position: relative;
   }

希望可以帮到你!

  • Ace_____ 提问者 #1
    我的意思是子元素在父元素里居中可以用margin吗?设置了绝对定位的话
    2017-07-06 16:49:31
  • 樱桃小胖子 回复 提问者 Ace_____ #2
    因为设置了绝对定位,绝对定位会使元素脱离文档流,因此设置了绝对定位后,margin:0 auto;会不起作用,需要使用绝对定位的位移量top/left/right/bottom结合margin结合来设置,课程中老师有讲解其使用方法的。
    2017-07-06 17:22:36
  • Ace_____ 提问者 #3
    非常感谢!
    2017-07-07 09:41:41
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师