子 div 在父 div 中完全居中

 HTML

<form action="">
  <div id="div1">
    <div id="div2">
      
    </div>
  </div>
</form>

a.第一种,justify-content(横轴居中),align-items(元素整体居中)

#div1 {
  border: 1px solid;
  width: 100px;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}

#div2 {
  border: 1px solid;
  width: 30px;
  height: 30px;
}

b.第二种,justify-content(横轴居中),align-self(小 div 自身纵轴居中)

#div1 {
  border: 1px solid;
  width: 100px;
  height: 100px;
  display: flex;
  justify-content: center;
}

#div2 {
  border: 1px solid;
  width: 30px;
  height: 30px;
  align-self: center;
}

c.第三种,定位法,父元素相对定位(relative),子元素绝对定位(absolute),div2 width = (div1 width - div2 width) / 2,height 同理!

#div1 {
  border: 1px solid;
  width: 100px;
  height: 100px;
  position: relative;
}

#div2 {
  border: 1px solid;
  width: 30px;
  height: 30px;
  position: absolute;
  left: 35px;
  top: 35px;
}

d.第四种,定位法,未知 div 宽高的时候

#div1 {
  border: 1px solid;
  width: 100px;
  height: 100px;
  position: relative;
}

#div2 {
  border: 1px solid;
  width: 30px;
  height: 30px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

注:translate 可以理解为在 x,y 轴上进行移动,想象屏幕中间有一个十字,div2 紧贴第四象限

然后利用 transform 属性,将其往平移 div 自身长度的50%,往平移 div 自身长度的50%,实现居中。

e.脱离文档流,margin 居中

#div1 {
  border: 1px solid;
  width: 100px;
  height: 100px;
  position: relative;
}

#div2 {
  border: 1px solid;
  width: 30px;
  height: 30px;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

设置 position 属性,上下左右均为 0(脱离文档流,并使其填充父级所有可用空间),

然后给 div 设置宽高,防止其占用父级所有可用空间,

最后再设置 margin:auto(等同于 margin-top:0;margin-bottom:0)使浏览器重新计算外边距,以达到垂直水平居中效果。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值