实现div中的div水平垂直居中

方法一

利用transform实现div居中,要先设置定位
css

.outer {
   width: 500px;
   height: 200px;
   background-color: green;
   position: relative;
        }

.inner {
   width: 20px;
   height: 10px;
   background-color: wheat;
   position: absolute;
}
.center {
   left: 50 %;
   top: 50 %;
   transform: translate(- 50 %, - 50 %);/*自己的50% */
}

html

<div class="outer">
    <div class="inner center"></div>
</div>

方法二

利用 margin: auto;要先设置定位

css

.outer {
  width: 500px;
  height: 200px;
  background-color: green;
  position: relative;
}

.inner {
  width: 20px;
  height: 10px;
  background-color: wheat;
  position: absolute;
}
.center {
   left: 0;
   top: 0;
   right: 0;
   bottom: 0;
   margin: auto;
}

html

<div class="outer">
    <div class="inner center"></div>
</div>

方法三

利用display:flex实现div居中
css

.flex{
	display:flex;
    align-items: center;
	justify-content:center;
	width:500px;
	height:500px;
    border:10px solid;
	}
.flex_son{
	width:100px;
	height:100px;
	border:10px solid;
}

html

<div class='flex'>
	<div class="flex_son"></div>
</div>

方法四

div绝对定位水平垂直居中【margin 负间距】 这或许是当前最流行的使用方法。


.outer {
    width: 500px;
    height: 500px;
    position: relative;
    background:red;
}
.center{
    width:200px;
    height: 200px;
    background:green;
    position: absolute;
    left:50%;
    top:50%;
    margin-left:-100px;//要宽度的一半
    margin-top:-100px;
}

<div class="outer">
    <div class="center"></div>
</div>

方法五

将父盒子设置为table-cell元素,可以使用text-align:center和vertical-align:middle实现水平、垂直居中。
子元素设置为inline-block;

.Aa{
    display: table-cell;
    text-align:center;
    vertical-align: middle;
    width: 500px;
    height: 500px;
    background:green;
    
}
.aa{
    display: inline-block;
    background:red;
    width: 100px;
    height: 100px;
}
<div class="Aa">
    <div class="aa"></div>
</div>

方法六

利用父基线跟伪元素:before搭配vertical-align:middle实现对齐

<style type="text/css">
  .parent {
    display: inline-block;
    width: 300px;
    height: 300px;
    font-size: 0;
    background: #798456;
    text-align: center;
  }
  .parent:before {
    display: inline-block;
    width: 20px;
    height: 100%;
    content: '';
    background: #132456;
    vertical-align: middle;
  }
  .child {
    display: inline-block;
    width: 50px;
    height: 50px;
    background: #19be6b;
    vertical-align: middle;
  }
</style>

<div class="parent">
  <div class="child">child</div>
</div>

方法(窗口居中)

利用vw,vh来实现
vw是可视窗口的宽度单位,和百分比有点一样,1vw = 可视窗口的宽度的百分之一。比如窗口宽度大小是1800px,那么1vw = 18px。和百分比不一样的是,vw始终相对于可视窗口的宽度,而百分比和其父元素的宽度有关。
只要设置margin的上下间距,使之height + margin-top +margin-bottom = 100 ,width + margin-left + margin-right = 100 ,就能够响应垂直居中

#aa { 
  width: 50vw; 
  height: 50vh; 
  margin: 25vh auto; 
  /*margin: 25vh 25vw; */ 
}
 	
<div id="aa"></div>

你可能感兴趣的:(html)