情景描述:父元素由一個設置了高度的元素撐起,另一個元素自動繼承父元素的高,並且兩元素在一行顯示。
現在情況
<style> .far{ border: 1px solid bisque; } .s1{ height: 150px; width: 100px; background-color: blue; display: inline-block; } .s2{ height: 100%; width: 50px; background-color: brown; display: inline-block; } </style> </head> <body> <div class="far"> <div class="s1"></div> <div class="s2"></div> </div> </body>
方法1:
設置父元素flex,子元素不設置高度
<style> .far{ border: 1px solid bisque; display: flex; } .s1{ height: 150px; width: 100px; background-color: blue; display: inline-block; } .s2{ width: 50px; background-color: brown; display: inline-block; } </style> </head> <body> <div class="far"> <div class="s1"></div> <div class="s2"></div> </div> </body>
方法2:
父元素相當定位,子元素絕對定位,設置100%高
.far{ border: 1px solid bisque; position: relative; font-size: 0; } .s1{ height: 150px; width: 100px; background-color: blue; display: inline-block; } .s2{ width: 50px; background-color: brown; display: inline; position: absolute; height: 100%; } </style> </head> <body> <div class="far"> <div class="s1"></div> <div class="s2"></div> </div> </body>
s1和s2元素都要設置inline或者inline-block屬性,否則不法自動在一行,要在設置left,top等屬性