html设置高度为设备高度一半,如何让子容器的高度等于父容器的宽度的一半

如下:有A容器和B容器,A容器宽度和高度已知,使用CSS满足如下条件:

B容器高度是A容器宽度的一半

B容器左右离A容器都是10px

B容器在A中上下居中

B容器内部文字水平垂直居中

277b50da7c59dbc4adad920c46b34379.png

这里面水平垂直居中不难实现,在上篇CSS 居中对齐中已经介绍,但是B容器高度为A容器width的一半如何实现呢?

可以用到margin 和 padding 的一个特性:百分比。 margin 和padding 的百分比是基于父元素的宽度。

如果A容器是视窗ViewPort,可以说使用 "vw" 单位来设置B容器的高度:50vw 即表示视窗宽度的一半

1. 弹性盒子实现居中,padding实现B容器高度控制,注意要把height设为0,这里用的默认的标准盒模型:content-box

.A{

background-color: beige;

height: 400px;

width: 400px;

//子元素水平垂直居中

display: flex;

align-items: center;

justify-content: center;

}

.B{

// 水平方向占满,左右保留10px

flex: 1;

margin: 0 10px;

// 高度为父亲容器一半

padding: 25% 0;

height: 0px;

background: wheat;

// 内部文案居中

display: flex;

justify-content: center;

align-items: center;

}

2. absolute 实现居中, padding实现B容器高度控制

.A{

position: relative;

height:400px;

width:400px;

background-color: beige;

}

.B{

position: absolute;

left: 0;

top:0;

right: 0;

bottom: 0;

margin: auto 10px;

padding: 25% 0;

height: 0;

background: wheat;

}

.text-content{

position: absolute;

left: 50%;

top: 50%;

transform: translate(-50%, -50%);

}

3. 若A是视窗,宽度为100vw ,高度为100wh,直接设置 B 高度为50vw即可

.B{

position: absolute;

left: 0;

top:0;

right: 0;

bottom: 0;

margin: auto 10px;

height: 50vw;

background: wheat;

}

.text-content{

position: absolute;

left: 50%;

top: 50%;

transform: translate(-50%, -50%);

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值