CSS样式之width: auto 100%与height:100%

本文详细介绍了CSS中width和height属性的使用,特别是width:auto和width:100%,以及height:100%的情况。当width设置为100%时,元素content等于父元素content,而在绝对定位下,它会相对于第一个非static的父元素。对于height:100%,如果父元素高度由内容撑开(height:auto),则子元素设置height:100%无效,解决方法是给父元素设定显式高度或使子元素绝对定位。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Width(默认情况下为content box的宽度)

width:auto

元素content+padding+border+margin=父元素的width

 <style>
        .parent {
            height: 400px;
            width: 400px;
            border: 1px solid black;
            padding: 10px 10px;
        }
        .son { 
            height: 400px; 
            /* content+border+padding+margin = 400px of parent*/
            width: auto;
            border: 1px solid red;
            padding: 0 2px;
            margin:  0 2px;
        }
    </style>
 <div class="parent">
        <div class="son"></div>
    </div>
width: 100%

元素content == 父content

 <style>
        .parent {
            height: 400px;
            width: 400px;
            border: 1px solid black;
            padding: 10px 10px;
        }
        .son { 
            height: 400px; 
            /* content = 400px of parent*/
            width: 100%;
            border: 1px solid red;
            padding: 0 2px;
            margin:  0 2px;
        }
    </style>
 <div class="parent">
        <div class="son"></div>
    </div>

注意: 当子元素为absolute 绝对定位时,width:100% 相对于第一个非static的父元素而言

2. height(默认情况下为content box的高度)

height: 100%

**现象:**当父元素的height:auto时(即高度由子撑开时),子元素(非绝对)height:100%不起作用:
因为: auto * percentage % == NAN
解决办法: 1. 为父提供一个显式高度值 2. 设置子元素为绝对元素
1. 父设置显式高度

 <style>
        .parent {
            height: 400px;
            width: 400px;
            border: 1px solid black;
            padding: 10px 10px;
        }
        .son { 
        /* height = 400px of parent */
            height: 100%; 
            width: 400px;
            padding: 10px 0px;
            border: 1px solid red;
        }
    </style>
     <div class="parent">
        <div class="son"></div>
    </div>

2. 子元素设置为绝对元素:此时子元素高度相对于content + padding of parent

 <style>
        .parent {
            height: 400px;
            width: 400px;
            border: 1px solid black;
            padding: 10px 10px;
            position: relative;
        }
        .son { 
        /* height = 400+20 of parent */
            height: 100%; 
            width: 400px;
            padding: 10px 0px;
            border: 1px solid red;
            position:absolute;
        }
    </style>
      <div class="parent">
        <div class="son"></div>
    </div>

注意:与width相同,这种 子元素为absolute 绝对定位时,height:100% 相对于第一个非static的父元素而言

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值