简体   繁体   中英

Prevent wrapping of text within divs, but not without

I have a set of tags in an outer div, like so:

╔════════════════════════════╗
║ ╔═══════╗╔═════╗╔═══╗╔═══════╗╔═══╗
║ ║ tag 1 ║║ t 2 ║║ 3 ║║ tag 4 ║║ 5 ║  👈❌
║ ╚═══════╝╚═════╝╚═══╝╚═══════╝╚═══╝
╚════════════════════════════╝

I want the tags to wrap like so:

╔═══════════════════════╗
║ ╔═══════╗╔═════╗╔═══╗ ║
║ ║ tag 1 ║║ t 2 ║║ 3 ║ ║  👈✅
║ ╚═══════╝╚═════╝╚═══╝ ║
║    ╔═══════╗╔═══╗     ║
║    ║ tag 4 ║║ 5 ║     ║
║    ╚═══════╝╚═══╝     ║
╚═══════════════════════╝

But no matter what I've tried, so far I can only get the overflow like in the first example, or wrapping within the inner divs, like this:

╔════════════════════════════╗
║ ╔═══════╗╔═════╗╔═══╗╔════ ║
║ ║ tag 1 ║║ t 2 ║║ 3 ║║ tag ║
║ ╚═══════╝╚═════╝╚═══╝╚════ ║  👈❌
║          ═══╗╔═══╗         ║
║           4 ║║ 5 ║         ║
║          ═══╝╚═══╝         ║
╚════════════════════════════╝

Is there anyway to get the desired behavior with just CSS, with the following criteria met?

Criteria

  • Inner divs never wrap internally (required)
  • Outer div hugs content height (required)
  • Inner div layout is centered horizontally within outer div (required)
  • Outer div hugs content width (preferred)
    • (or, acceptable-but-undesired) Outer div has fixed-width

You need to set a display of inner div to display: inline-block and provide a width for the outer div. Then, you're good to go!

 #main{ width: 400px; border: 2px solid #ccc; background: #e9e9e9; margin: 5px; float: left; } .inner{ width: 130px; height: 130px; margin: 10px; padding: 10px; float: left; background: RGBA(200,30,30,0.4); } 
 <div id="main"> <div class="inner"> <h1>Tag1</h1> </div> <div class="inner"> <h1>Tag2</h1> </div> <div class="inner"> <h1>Tag3</h1> </div> <div class="inner"> <h1>Tag4</h1> </div> <div class="inner"> <h1>Tag5</h1> </div> </div> 

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