CSS styling for a container element that enables word wrapping on child divs, while also being able to stretch to accommodate the width of its children

Is it feasible to create CSS that allows an element to support word-wrap:break-word, while also adjusting its width to fit the content when breaking is not possible?

<html>
  <style>
  .outer {
    background-color:red;
    word-wrap:break-word;
  }
  </style>
  <div class="outer">
    User generated content:
    <a href="http://www.google.com">http://anannoyinglylongurlthatcausesthepagetogrowtolongunlessIusewordwrapbreakwordasdfasfasdfasdfasdfasdfasdfsadfasdfadsf</a>
    <table>
      <tr>
        <td>asdfasdfadsffdsasdfasdfsadfafsd</td>
        <td>asdfasdfadsffdaasdfassdffaafasds</td>
      </tr>
    </table>
    <img src="http://www.google.com/intl/en_com/images/srpr/logo3w.png"/>
  </div>
</html>

In the provided example, the URL breaks correctly, but the table and image overflow the red outer div if the window width decreases.

Changing the outer div to display:inline-block or display:table causes it to adjust properly to accommodate the content, but the URL no longer breaks if the window is narrower than the URL.

This solution needs to be specific to WebKit (on Android) and should ideally be achieved through CSS only, without relying on Javascript.

Answer №1

If I have correctly understood your requirements, all that is needed is to set overflow: auto on the .outer element. Check out this example: http://jsfiddle.net/hgLbh/1/ (tested on both safari and chrome).

Update:

After considering your comment regarding scrolling, I explored alternative solutions and I found one that addresses that issue as well. It may not be the cleanest solution, but it seems to work (at least in my local safari).

The workaround involves duplicating your content and enclosing the duplicate within two additional div elements. Consequently, the HTML structure will resemble:

<div class="outer-fixed">
    <div class="just-a-helper-wrapper">
        ... original user-generated content
    </div>
</div>
<div class="outer">
    ... same original user-generated content
</div>

As for the CSS:

.outer,
.outer-fixed {
    background-color: red;
    word-wrap: break-word;
    position: absolute;
    left: 0;
    right: 0;
}

.outer-fixed {
    position: fixed;
    right: 0;
}
.outer-fixed * {
    visibility: hidden;
}

It's worth noting that the use of `just-a-helper-wrapper` is essential because `outer-fixed *` does not target text nodes directly. For instance, the text "User-generated content:" from your example would still be visible if not for this additional wrapper. You can remove it if such content is not present.

Here's the updated link: http://jsfiddle.net/hgLbh/2/

Answer №2

By setting width: 100%; and applying table-layout: fixed;, the td cells are constrained to fit within the table, facilitating text wrapping.

  table {
        width:100%;
        table-layout:fixed
      }

Answer №3

I'm not sure how it will behave on mobile webkit, but this code snippet worked perfectly in Chrome.

Check out the code here

.outer {
    background-color:red;
    word-wrap:break-word;
    overflow:hidden;
  }

.outer table {
    width: 100%;
    table-layout:fixed
}

.outer * {
    max-width: 100%;
}

Answer №4

It appears that draevor may have found the solution, although it seems like you're hoping to avoid a scrollbar appearing in the middle of the screen within the div element. If this is the case, and depending on your specific restrictions, you could experiment with this approach to turn the div into a viewport:

Custom CSS

html {height: 100%}
body {overflow: auto; height: 100%; margin: 0;}
.outer {
    word-wrap: break-word; 
    background-color: red;
    overflow: auto;
    min-height: 100%;
}

Answer №5

After delving into the depths of the CSS specification, it seems that achieving my desired outcome may be a challenging task due to the complexity of size calculations. Here are some key insights I gathered:

http://www.w3.org/TR/CSS21/visudet.html

The content width of a non-replaced inline element's boxes is determined by the rendered content within them.

To ensure that the background of my containing box expands to match the width of its children, it seems crucial to establish an inline formatting context for its layout:

http://www.w3.org/TR/CSS21/visuren.html#normal-flow

In cases where an inline box exceeds the width of a line box, it gets split into multiple boxes distributed across different line boxes. If splitting is not possible, the box overflows the line box.

It would be beneficial if the breaking rules also account for emergency wrapping scenarios.

http://www.w3.org/TR/2010/WD-css3-text-20101005/#word-wrap

This property determines whether the UA can break within a word to prevent overflow when dealing with excessively long unbreakable strings.

Unfortunately, the clarity provided by this information is limited. Let's explore the newer draft spec:

http://www.w3.org/TR/css3-text/#overflow-wrap

Break opportunities beyond 'overflow-wrap: normal' line breaking do not factor into calculating 'min-content' intrinsic sizes.

Although somewhat ambiguous, if 'min-content' intrinsic sizes are linked to the same calculations determining line-breaking possibilities, my prospects may be dim.


In the end, resorting to JavaScript became necessary to measure the content and make decisions regarding displaying it in block or inline context. A bit disheartening, but practical nonetheless.

var messages = document.body.getElementsByClassName('mail_uncollapsed');

// Show overflowing content by setting element display to inline-block. This
// prevents break-word from being applied to the element, so we only do this
// if the element would overflow anyway.
for (var i = 0; i < messages.length; ++i) {
  var message = messages[i];
  message.style.display = 'block';
  var isOverflowing = message.clientWidth < message.scrollWidth;
  if (isOverflowing) {
    message.style.display = 'inline-block';
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Safari div not exhibiting proper overflow functionality

I'm looking to set up a webpage with a single sidebar and content area. Here's how I envision it: <div id="mainWrapper"> <!-- Sidebar --> <div id="sidebar"> <p>Sidebar</p> <p>Sidebar< ...

Dynamically switch between showing more and showing less content on each div

Whenever the specific show more button is clicked, the content should be displayed without causing the entire component to re-render. I have tried using a useState, but each time the button is clicked, the whole component re-renders, resulting in long load ...

How to position a Bootstrap 4 button group at the bottom of a flexbox container

I am working with HTML code that looks like this: <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/> <div class="border d-flex align-items-baseline m-2 p-2" style="width: 400px"> < ...

Integrate blogger into my website with automatic height adjustment and scrolling functionality

Check out my website here. I've integrated a blogger component into it. Can anyone provide guidance on creating parallel scroll and automatically resizing sections based on the blog's height? Thanks, M ...

What is the best way to position an image next to an input element?

How can I position submit.png next to the input element in my code? <div class="input-box" style="height: 40px; width: 500px;"> <img src="img/delete.png" width="25px" height="25px;" style="position: absolute; right: 0;"> ...

Mudblazor - Tap or click within the designated area to trigger the drag and drop functionality

I have incorporated the Mudblazor CSS framework into my Blazor WebAssembly project. Within the drag and drop zone, I have included a button that is supposed to remove each uploaded image. However, when I click on the remove button, it only opens up the fi ...

Tips for modifying the default settings of a CSS framework like Material UI

Exploring the realm of CSS for the first time and feeling a bit lost. I am working with material ui alongside react and redux. My goal is to customize certain properties of a specific component, such as TextField with the disabled attribute. Upon inspectin ...

What causes webkit browsers to reduce the size of certain floating elements on mobile devices?

Struggling to create a responsive layout for a web app, specifically dealing with rendering issues on mobile webkit browsers. The floating elements are shrinking in an unpredictable way, causing problems on Chrome and Safari for Android and iOS devices. ...

Creating a Dropdown Filter using Vanilla JavaScript

I am currently working on a project for one of my college courses, which involves creating a dropdown list filter using pure JavaScript to filter a grid of images in HTML/CSS. The main challenge I am facing is that this filter needs to be able to work with ...

What is the correct way to maintain focus on a nested scrolling div over another scrolling div with jQuery?

I have encountered an issue with a modal view that contains content extending beyond its boundaries. To remedy this, I applied the overflow-y: scroll property. However, the problem arises when the modal view overlaps with the body, which also has scrolling ...

The most sophisticated method for creating a 2x2 grid of divs

I have developed a quiz application similar to Buzzfeed with four answer options for each question. The layout on mobile devices is satisfactory, displayed in a 2x2 grid. However, when viewing the app on desktop screens, the answers appear horizontally in ...

Troubleshooting: Issues with Integrating Javascript and CSS into

I'm still new to this platform, so please correct me if I make any mistakes. My goal is to create a "task table" that allows users to edit existing tasks and add new ones. Thanks to the base template provided by Ash Blue, I've managed to program ...

In React, I'm unable to navigate to a different page

My English may not be the best, but I am working on creating a Login Page. The issue I'm facing is that when I click the Login button, I want to navigate to the Home Page I designed using React. However, whenever I try to implement Link or Route comma ...

Why is the 3D CSS transform (translateZ) feature malfunctioning on Android 4.0.3?

I have this HTML code that is functioning well on Chrome, Safari, and Mobile Safari. However, when testing it on Android 4.0.3, the translateZ property does not seem to have any desired effect on the div element. While everything else works as expected, ...

Tips for pausing keyframes animation on its final animation frame

Is there a way to halt my animation at the 100% keyframe? What I'm attempting to accomplish is animating these boxes so that when you click on the top one, it moves to the bottom and vice versa. Any suggestions or ideas on how to achieve this? <h ...

Optimizing responsiveness and side margins for high-resolution displays

Struggling with creating a website design with Bootstrap. My goal is to add margins on the sides when the screen size increases, but once I achieved it, the responsiveness of the page got disrupted. To incorporate the side margins, I enclosed the entire b ...

Text Module of the Divi theme

Issue Resolved (After noticing that Divi was adding padding twice to <ul>'s in their footer and Text Module, I created a new class to remove the padding-bottom from the sub-list item.) In a Divi text module, I created an unordered list with a s ...

What is the best way to ensure that the child flex box matches the height of the parent flex box by 100%?

As a beginner, I'm venturing into creating an experimental site for myself. However, I am facing an issue where the .menu-container does not seem to stretch 100% the height of the .container. You can view the code on jsfiddle: https://jsfiddle.net/y1 ...

Adjusting the Stripe Button to Utilize a Unique Button Class

I have a stripe button on my website and I want to add my custom class to it. I discovered that manually creating the CSS for it can work, but I prefer to maintain consistency across all buttons on my site by using my custom class. No matter what I attemp ...

A data table created with Bootstrap is not displayed inline with the pagination feature

Customizing Bootstrap Data Table Code Instructions on how to customize this code: <div class="row"> <div class="col-sm-5"> <div class="dataTables_info" id="example_info" role="status" aria-live="polite"> Showing 1 to 10 of 2 ...