div嵌套div的居中问题

    div嵌套div,我们经常都用。布局是基础,扎实的基础会让你在解决问题的时候更柔韵有余。这是我出来工作之后深深的领悟。下面是我对外层布局的一些小总结。

<!DOCTYPE HTML>
<html>
<head>
<title>div嵌套div居中问题</title>
  <meta http-equiv="content-type"content="text/html; charset=UTF-8"/>
  <style type="text/css">
  .BD-one{
    width:200px;
	height:200px;
	background-color:red;
  }
  .content-one{
    width:40px;
	height:40px;
	background-color:yellow;

	margin:0 auto; /* 这是最经常用到的 */
  }


  .BD-two{
    width:200px;
	height:200px;

	background-color:green;

	/* 这里的 父容器需要有position的设置,无论是relative 还是 absolute */
	position:relative;
  }
  .content-two{
    width:60px;
	height:40px;
	background-color:yellow;

    position:absolute;
	/* 这里的 top left:50%都是相对于父容器的 */
	top:50%;
	left:50%;
	/* 这里的 margin-top margin-left:-20px都是相对于自己的。设置不同的值查看效果 */
	margin-top:-20px; /* 40/20 */
	margin-left:-30px; /* 60/20 */
  }

  .BD-three{
    /* 最外层 用百分比 就不行了 */
	/* 如这里width:100%;  height:100% */
    width:900px;
	height:300px;
	background-color:blue;
  }
  .BFB{
    /* 父容器用%也是可以的 */
    width:20%;
	height:20%;
	background-color:red;

	/* 这里的 父容器需要有position的设置,无论是relative 还是 absolute */
	position:relative;
  }
  .content-three{
    width:40px;
	height:40px;
	background-color:yellow;

    position:absolute;
	/* 这里的 top left:50%都是相对于父容器的 */
	top:50%;
	left:50%;
	/* 这里的 margin-top margin-left:-20px都是相对于自己的 */
	margin-top:-20px;
	margin-left:-20px;

  </style>
</head>
<body>
  <span>这里针对的是静态的HTML元素</span>
  <span>如果是动态生成的元素,JS会更好</span>

  <span>左右居中</span>
  <div class="BD-one">
    <div class="content-one"></div>
  </div>

  <br/>

  <span>上下左右居中</span>
  <div class="BD-two">
    <div class="content-two"></div>
  </div>

  <span>上下左右居中,父容器采用%的情况</span>
  <div class="BD-three">
    <div class="BFB">
      <div class="content-three"></div>
    </div>
  </div>
</body>
</html>

才疏学浅,如有建议或者意见,望留言指正。

(●'◡'●)

转载于:https://my.oschina.net/u/2870138/blog/782529

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值