純css+基於body的子集div的水平垂直居中


小果今天要實現這樣的效果:單純css樣式,實現body下子集的水平垂直居中。

body內容:

<body>
    <div class="div1">
       	<div class="div2"></div>
    </div>
</body>

效果:

通過一系列的嘗試,實現了四種方法,驚奇的發現,其中三個是用position:absolute實現的:(div大小確定)

1.原理:position: absolute;top: 50%;left: 50%;margin-top: -50px;margin-left: -50px;

<style type="text/css">
  html,body{
	height:100%;
	width:100%;
	background: black;
	}
  .div1{
	height: 100px;
	width: 100px;
	position: absolute;
	top: 50%;
	left: 50%;
	margin-top: -50px;
	margin-left: -50px;
	background: pink;
	}
  .div2{
	height: 10px;
	width: 10px;
	margin-top: 90px;
	background: lightblue;
	}
</style>

2.原理:margin: auto;position: absolute;top: 0;right:0;bottom: 0;left: 0;

<style type="text/css">
  html,body{
    height:100%;
    width:100%;
    background: black;
    }
  .div1{
	height: 100px;
	width: 100px;
	margin: auto;
	position: absolute;
	top: 0;
	right:0;
	bottom: 0;
	left: 0;
	background: pink;
	}
  .div2{
	height: 10px;
	width: 10px;
	margin-top: 90px;
	background: lightblue;
	}
</style>

3.原理:transform:translate(-100px,-100px);position: absolute;top: 50%;left: 50%;

<style type="text/css">
  html,body{
	height:100%;
	width:100%;
	background: black;
	}
  .div1{
	height: 100px;
	width: 100px;
	margin: auto;
	position: absolute;
	top: 50%;
	left: 50%;
	background: pink;
	-webkit-transform:translate(-100px,-100px);
	transform:translate(-100px,-100px);
	}
  .div2{
	height: 10px;
	width: 10px;
	margin-top: 90%;
	background: lightblue;
	}
</style>

4.原理:display:flex;justify-content:center;align-items:center;

body是這樣子的:

<body>
    <div class="div1"></div>
    <div class="div2"></div>
</body>

css:

<style type="text/css">
  html,body{
	height:100%;
	width:100%;
	background: black;
	display: flex;
	justify-content: center;
	align-items: center;
	}
  .div1{
	height: 100px;
	width: 100px;
	background: pink;	
	}
  .div2{
	height: 10px;
	width: 10px;
	position: absolute;
	left: 50%;
	top: 50%;
	margin-top: 40px;
	margin-left: -50px;
	background: lightblue;
	}
</style>

以上是div1的大小確定的居中方法,那如果大小不知道呢?小果使用了paddingO(∩_∩)O

代碼君:(display: table-cell必不可少啊)

 body內容:

<body>
    <div class="div1">
       	<div class="div2"></div>
    </div>
</body>

css內容:

<style type="text/css">
  html,body{
	height:100%;
	width:100%;
	background: black;
	}
  .div1{
	padding: 50px;
	display: table-cell;
	position: absolute;
	top: 50%;
	right:50%;
	bottom: 50%;
	left: 50%;
	background: pink;
	margin: auto;
	}
  .div2{
	padding: 10px;
	margin-top: 30px;
	margin-left: -50px;
	background: lightblue;
	}
</style>

 然而,效果是這樣的:

好了,整理完畢。如果果果大軍們有什么意見,或者更好的方法,歡迎交流,隨之奉陪哈,謝謝!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM