简体   繁体   中英

Html element not taking up its full width with absolute positioning and inside flexbox

This gray block ( https://jsfiddle.net/var6u4g7/ ) on the right doesn't take up the full width of it's content. It's using the size of the righttext , if you add more words in the righttext element you'll see the grey box is taking up exactly that width. I don't want to assign a fixed width because I don't know how much will be inside it, so I want it to be as wide as its content.

If you remove display: flex on the first element then the width works but other things break. (If you remove the grey box you'll see why I need display: flex . The grey box only appears sometimes, and when it's not there all the content in that row should be vertically center aligned. Is there a way to make this work?

 .container { display: flex; align-items: center; background-color: yellow; } .leftside { margin-right: auto; } .rightside { position: relative; } .righttext { background-color: red; margin-top: 10px; margin-bottom: 10px; } .absolute { position: absolute; right: 0; top: 0; background-color: gray; } 
 <div class="container"> <div class="leftside">Lorem ipsum dolor sit amet.</div> <div class="rightside"> <div class="righttext"> Lorem ipsum. </div> <div class="absolute"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. </div> </div> </div> 

It's unclear from the question exactly what you are looking for, but if I do understand correctly, you want the red and gray boxes to be full-width. You can do this by adding flex: 1 to .rightside and width: 100%; to .absolute . The flex property indicates that a certain element should take priority. It's shorthand for flex-grow: 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM