An Innovative Styling Technique Using CSS and jQuery
Imagine a scenario where the HTML structure can be modified to have the .left
element come before the .right
element:
<div class="frame">
<div class="left">Lorem ipsum dolor sit amet, c...</div>
<div class="right">
<div class="color-wrap">I adjust my width ...</div>
</div>
</div>
For wide screens, consider applying the following CSS rules:
.frame {
background-color: lightgreen;
width: 80%;
padding: 12px;
overflow: auto;
}
.left {
background-color: #709670;
border: 1px solid black;
display: table-cell;
}
.left .color-wrap {
}
.right {
display: table-cell;
width: 200px;
vertical-align: top;
}
.right .color-wrap {
background-color: #127212;
color: white;
border: 1px solid black;
display: inline-block;
}
For smaller screens, utilize media queries as shown below:
@media screen and (max-width: 700px) {
.left {
display: block;
}
.right {
display: block;
width: auto;
}
.right .color-wrap {
display: block;
width: auto;
color: yellow;
}
}
To address cases where the .right
element contains only a single line of text, you can use either fixed widths or a combination of max-width and min-width within a table-cell
layout.
If you wish to apply a background color specifically to the text portion, employ a wrapper element such as .color-wrap
for targeted styling.
Another consideration is adjusting the width of the .right
element dynamically using jQuery for scenarios involving single-line content:
var rightCellMaxWidth = parseInt($(".right").css("width"));
function fixRightCellWidth() {
$(".right .color-wrap").each(function () {
var rightCellWidth = $(this).outerWidth();
var rightCellType = $(this).css("display");
if (rightCellWidth < rightCellMaxWidth
&& rightCellType == "inline-block") {
$(this).parent().width(rightCellWidth);
} else {
$(this).parent().removeAttr("style");
}
});
}
$(window).resize(function () {
fixRightCellWidth();
});
fixRightCellWidth();
By determining the width and display type of the elements, this script adjusts the container width accordingly. For larger screens, it matches the .right .color-wrap
width, while reverting to default styling for smaller views or multi-line content.
For a live demonstration, refer to this fiddle: http://jsfiddle.net/audetwebdesign/N4KE2/
Note on Design
In absence of JavaScript/jQuery functionality, the layout gracefully degrades to a fixed-width format, ensuring usability across different devices.