I have an HTML document with a div, meant to be colored in the background under some text or an image (I have both happening on different websites right now). A minimal case:
<!doctype html>
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
</head>
<body>
<header>
<div style="min-width: 400; background-color: black">
<div style="font-size: x-large; color: red">
A_Fairly_Long_Word_Or_Image
</div>
</div>
</header>
</body>
</html>
The problem I find is this: If the browser window (tested in both Firefox 47 and IE 11) is made very narrow, and then we scroll to the right, the div background color does not fill all the way to the end of the text or image (whether the min-width specifier is there or not). As shown below:
On the other hand, if the DOCTYPE specifier is removed, then it actually does work as expected:
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
</head>
<body>
<header>
<div style="min-width: 400; background-color: black">
<div style="font-size: x-large; color: red">
A_Fairly_Long_Word_Or_Image
</div>
</div>
</header>
</body>
</html>
The code on top does pass an online validator when I test it. How can this be fixed (and explained)?
The reason why the background doesn't go all the way to the right is:
By default a block element like <div>
occupies the entire width of the parent, given there is no blank space in the text sample - A_Fairly_Long_Word_Or_Image
, which means it renders as a single word, and won't wrap, so the the text overflows in a smaller viewport, but not for the background that sets on the div.
However, under quirks mode (without a doctype), it behaves differently, according to this article:
Overflow is treated by expanding a box. When the content of an element does not fit into the dimensions specified for it (explicitly or implicitly), then overflow: visible (the default) means that the content overflows while the box dimensions are as specified. In Quirks Mode, the dimensions change; this can easily been seen e.g. if the box has a background color or a border.
How to fix that within standard mode?
Please use the standard HTML5 <!doctype html>
it is highly recommended. You can set the container div to display: inline-block;
+ min-width: 100%;
, As the size of an inline block depends on the content inside, and the min width will make it to expand even if the viewport is larger, check out the jsFiddle, resize the output frame and see.
.container {
background-color: black;
font-size: x-large;
color: red;
display: inline-block;
min-width: 100%;
}
<div class="container">A_Fairly_Long_Word_Or_Image</div>
Well, if you do want the text to wrap, simply apply word-break: break-all;
- jsFiddle.
.container {
background-color: black;
font-size: x-large;
color: red;
word-break: break-all;
}