Html – Display a div only if there is enough space, and hide it if there isn’t

csshtml

I have a table with a date column. Each date looks like

Wednesday, 08.06.2011

When the width of the browser window is too narrow, I want to only display the date without the day of the week to conserve horizontal space. Like this

08.06.2011

An ideal solution would allow a markup like

<div class="weekday">Wednesday, </div><div class="date">08.06.2011</div>

and be entirely css-based without involving JavaScript. But if that is not possible I could live with a JavaScript-based solution.

Best Answer

You need some scripting here. CSS can't do action based on some element's property like width. Just add simple javascript command in head of you script, e.g. in jQuery:

$(document).ready(function () {
    if ($(window).width() < 1024) 
        $('body').addClass('too-narrow');
});

Then do rest in CSS.

EDIT:

Actually there is CSS solution to this if you really want it.

.row { height: 30px; background: red; color: white; overflow: hidden; }
.row120 { width: 120px; }
.row200 { width: 200px; }
.row .other { height: 30px; float: left; }
.row .date,
.row .weekday { height: 30px; float: right; }
<div class="row row120">
    <div class="other">Tilte</div>
    <div class="date">18.04.2010</div>
    <div class="weekday">Wednesday</div>
</div>
<div class="row row200">
    <div class="other">Tilte</div>
    <div class="date">18.04.2010</div>
    <div class="weekday">Wednesday</div>
</div>

You need to have set height for both row div and other/date/weekday divs. Set those two to be floated right and all other (earlier) fields to float left. Worked for me on Chrome (showing Title 18.04.2010), not sure how others.