Display div only if there is enough space and hide it if not

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

Wednesday, 06/08/2011

When the width of the browser window is too narrow, I want to show the date without a day of the week to maintain horizontal space. Like this

06/08/2011

An ideal solution would allow type markup

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

and completely css-based without JavaScript. But if that is not possible, I could live using a JavaScript based solution.

+4
source share
5 answers

You need some scripting here. CSS cannot perform actions based on some element property, such as width. Just add a simple javascript command to the header of your script, for example in jQuery:

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

Then take a rest in CSS.

:

, CSS, .

.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>
Hide result

div, /date/weekday div. , ( ) , . Chrome ( 18.04.2010), .

+4

"", . : http://www.javascripter.net/faq/browserw.htm

, " " , ( ..), , , JavaScript, div #weekday.

+1

javascript. HTML, . , .

<div id="container">
    <div id="daydisplay" class="weekday">
        Wednesday
    </div>
    <div class="date">
        08.06.2011
    </div>
</div>

javascript . YUI JQuery , , , , widthOfScreen, . , left, .

var container = document.getElementById('container'),
containerWidth = container.clientWidth || container.scrollWidth;

if (containerWidth + x > widthOfScreen) {
   document.getElementById('daydisplay').style.display = 'none';
}

That should do the trick.

0
source

This is a pretty ugly solution, but if you want whole words to disappear, there is no better CSS technique than using overflow: hidden.

I changed your markup a bit ... maybe you can come up with something better, but hopefully this points in the right direction for a clean CSS solution:

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

CSS

div {
    background: #ccc;
    height: 18px;
    margin: 0 0 5px;
    overflow: hidden; }
span { float: right; }
span.weekday { 
    float: left;
    padding: 0 4px; }

See: http://jsfiddle.net/EQTBa/

0
source

Use the multimedia query for narrow windows, and then define the weekday class as display: none.

0
source

All Articles