简体   繁体   中英

Problems with auto width using CSS

<div class="outer">
  <div class="inner"></div>
  <div class="outer">
    <div class="outer"></div>
  </div>
</div>

I want to ajust the outer element's width using CSS.

Here is the requirement:

  1. the outer has a padding of 8px
  2. if inner is smaller than 200px - 16px , then outer is 200px
  3. if inner is greater or equal to 200px - 16px , then outer 's width is inner's width + 16px
  4. outer may has children of outer , and the inner outer element has the same requirement.

For example:

<div class="outer">
  <div class="outer">
  </div>
</div>

the outer outer has a width of 200px + 16px , the inner outer has a width of 200px

Use min-width

#outer{
     min-width:200px;
 }
#inner{
     width: auto;
}

This will cause outer to grow with inner but not below 200px

I commented on TheValyreanGroup's answer on how to make his/her answer work for your purpose. Basically you just have to add display:inline-block to prevent the outer div from taking up 100% width. Here is a demonstration:

 .outer { padding:8px; min-width:200px; display:inline-block; } /* These are for demonstration */ .outer { background-color:red; } .outer > .outer { background-color:purple; } .outer > .outer > .outer { background-color:blue; } 
 <div class="outer"> <div class="inner" contenteditable="true">test</div> <div class="outer"> <div class="outer" contenteditable="true">test test test test test</div> </div> </div> 

I added background colors just to demonstrate. I added contenteditable="true" so you can directly edit the text to observe its behavior.

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-2024 STACKOOM.COM