CSS div fixed height, min width but expands width on content - javascript

The title says it all really, but despite several tries I cant actually get this to work.
Im looking for a DIV to have a fixed height, and min-width, I will display text in the div (dynamically changing), should any text be long enough to reach the bottom of DIV I want the the width of the div to increase to accomodate all the text.
Is there a CSS solution ?

From what I've gathered, here is what I got
https://jsfiddle.net/Lu3tu98b/2/
div{
padding: 20px;
background-color: wheat;
}
.myDiv {
height: 100px;
min-width: 150px;
overflow: scroll;
}
Could you please provide your code.

OK, so its not possible to do this in CSS, so Javascript is the way to go.
For anyone else searching for a similar solution here is the javascript routine that I built to give me the functionality I required.
Basically it checks if the div is in overflow and if so increases the width by 5% increments until the overflow is resolved, if on load the div isnt in overflow it decreases the width by 5% until it finds the overflow point then steps back one notch.
function changedivsize(){
widthmin = 35; // in percent
widthmax = 80; // in percent
modified = false; // flag to signify when wheve modified the div larger
while ( $("#quotation").prop('scrollHeight') > $("#quotation").height() ) { // if div is in overflow
modified = true; // set flag so we dont start making div smaller in section below
var widthpixels = $('#quotation').width();
var parentWidth = $('#quotation').offsetParent().width();
var widthpercent = 100*widthpixels/parentWidth; // find current width % of div (3lines)
if (widthpercent < widthmax) { // if not at limit
widthpercent = Math.round(widthpercent+5); // add 5%
$("#quotation").width(widthpercent+"%"); // change div width
}else{
break; // if we are at limit call it a day
}
} // repeat adding 5% until either we are out of overload or at limit
while (modified == false){ // basically same as above but reduce div for smaller texts
var widthpixels = $('#quotation').width();
var parentWidth = $('#quotation').offsetParent().width();
var widthpercent = 100*widthpixels/parentWidth;
if (widthpercent > widthmin) {
widthpercent = Math.round(widthpercent-5);
$("#quotation").width(widthpercent+"%"); // change div width
if ( $("#quotation").prop('scrollHeight') > $("#quotation").height() ){
widthpercent = widthpercent+5;
$("#quotation").width(widthpercent+"%"); // change div width
break;
}
}else{
break;
}
}
};

Is this good for what you need?
http://jsfiddle.net/KefJ2/343/
#container {
position: relative; /* needed for absolutely positioning #a and #c */
padding: 0; /* will offset for width of #a and #c; and center #b */
border: green 3px dotted; /* just for the show */
float: left; /* To dynamicaly change width according to children */
height: 300px;
}
#a {
white-space: nowrap;
}

Related

Dynamically adjust a div's css zoom to fit container's size

Suppose such html code:
<editor>
<tree></tree>
</editor>
In my application, the tree is used to store user's input, for example:
'123'
'1111111111111111111111111111111111111111111111111111111'
So overflow is possible if text is too long.
I'd like to apply a css 'zoom' style to tree, to ensure it's size is smaller than editor.
How can I calculate the prefect zoom, using JavaScript?
You can effectively just scale it down step by step until it fits in the container.
Effectively this is:
Styling the elements so they will naturally overflow
Stepping down the scale 5% at a time
Stopping once the child element is smaller than it's parent
function calcSize() {
// The elements we need to use and our current scale
var editor = document.getElementById("editor")
var tree = document.getElementById("tree")
var scale = 1;
// Reset the initial scale and style incase we are resizing the page
tree.classList.add("loading");
tree.style.transform = "scale(1)";
// Loop until the scale is small enough to fit it's container
while (
(editor.getBoundingClientRect().width <
tree.getBoundingClientRect().width) &&
(scale > 0) // This is just incase even at 0.05 scale it doesn't fit, at which point this would cause an infinate loop if we didn't have this check
) {
// Reduce the scale
scale -= 0.05;
// Apply the new scale
tree.style.transform = "scale(" + scale + ")";
}
// Display the final result
tree.classList.remove("loading");
console.log("Final scale: " + Math.round(scale * 100) / 100)
}
// Run on load and on resize
calcSize();
window.addEventListener("resize", calcSize);
#editor {
display: block;
max-width: 50%;
font-size: 20px;
border: 1px solid #000;
overflow: visible;
}
#tree {
display: inline-block;
white-space: nowrap;
/* This is important as the default scale will be relative to the overflowed size */
transform-origin: 0 50%;
}
#tree.loading {
opacity: 0;
}
<editor id="editor">
<tree id="tree" class="loading">This is some overflowing text This is some overflowing text.</tree>
</editor>
(Try viewing the snippet in fullscreen and resizing the window to see it in effect)

make div 100% of browser height depending on length of content

I have 2 divs, a navigation and a main content in a bootstrap grid system. The length of either can vary depending on amount of content. I need them both styled to fill 100% of the browser window IF neither has the content to reach the bottom naturally. But if at least one of the divs has more content than the length of the browser window, I need to be able to scroll down the page with the styles of both divs remaining in tact and both have a height of the longer of the 2 divs.
I'm currently using a javascript resize function which seems to work but not in the case where neither div is long enough to fill the height of the browser window. Any suggestions?
HTML
<div class="row">
<div id="nav" class="col-xs-2">
Variable Height Navigation
</div>
<div id="main" class="col-xs-10">
Variable Height Content
</div>
</div>
Javascript
function resize() {
var h = (document.height !== undefined) ? document.height : document.body.offsetHeight;
document.getElementById("nav").style.height = h + "px";
}
resize();
window.onresize = function () {
resize();
};
I am trying to understand you question, and if I'm correct what you are looking for is:
Both divs need to be equally high
They need be at least the height of the screen
They need to take the height of the highest div
So let's try to achieve this goal as simply as possible:
var main = document.getElementById('main');
var nav = document.getElementById('nav');
function resize(){
var highest;
// Set the divs back to autosize, so we can measure their content height correctly.
main.style.height = 'auto';
nav.style.height = 'auto';
// Find the highest div and store its height.
highest = main.clientHeight > nav.clientHeight
? main.clientHeight
: nav.clientHeight;
// Check if the highest value is the div or the window.
highest = highest > window.innerHeight
? highest
: window.innerHeight;
// Assign the newly found value
main.style.height = highest + 'px';
nav.style.height = highest + 'px';
}
resize();
// Also, you don't need to wrap it in a function.
window.resize = resize;
// However, better would be:
window.addEventListener('resize', resize, false);
#main, #nav {
width: 100%;
height: auto;
}
#main { background: red; }
#nav { background: green; }
<div id="main"></div>
<div id="nav"></div>
Now, If you aren't bothered with the actual sameness in heiught of both divs but just want them to at least be one screenful, you should consider using CSS:
html, body { height: 100%; }
#nav, #main { min-height: 100%; }
I think that is the better solution (no Javascript!) and sort-of does what you want, bar the fact that you won't have to equally high div elements. However, you would barely notice it as each will at least fill the page.
You could try using viewport height:
For example:
#nav {
min-height: 100vh;
}
#main {
min-height: 100vh;
}
See Bootply.
This will also remove the need for JavaScript.

Adjust text size dynamically within div and also responsive

I have two working JSFiddle which I want to combine and work together.
JSFiddle-1 : http://jsfiddle.net/MYSVL/3050/
window.onresize=function() {
var child = $('.artist');
var parent = child.parent();
child.css('font-size', '18px');
while( child.height() > parent.height() ) {
child.css('font-size', (parseInt(child.css('font-size')) - 1) + "px");
}
Here the text inside artist container is responsive and its stretching to maximum font size when the screen is bigger. Its also shrinking to smallest font size when screen size is smaller.
JSFiddle-2 : http://jsfiddle.net/MYSVL/3047/
function calcDivHeights() {
window.onresize=$(".artist").each(function () {
var child = $(this);
var parent = child.parent();
//child.css('font-size', '18px');
while (child.height() > parent.height()) {
child.css('font-size', (parseInt(child.css('font-size')) - 1) + "px");
}
});
}
Here the function is checking for every artist div and adjusting the font size according to the while condition but I am unable to make it responsive like my JSFiddle-1 . Once the text size is smaller it remains smaller even I make the screen bigger. I want my JSFiddle-2 to work exactly as JSFiddle-1 so that I can maintain the responsiveness of the text according to screen size.
Can someone please help me out or feel free to modify my JSFiddle-2 in order to achieve the goal.
Thanks in advance
I can't see differences between your two fiddles except for the commented child.css('font-size', '18px'), both should do the same thing.
Your second fiddle seems to not works properly because once you resize window to a smaller resolution, child becomes smaller or equal to parent. Then, when you return on bigger resolution, you call again while( child.height() > parent.height() ), but now your child height is not greater than your parent height.
I think the following will just do what you're asking for:
$(document).ready(function () {
function adjustFontSize() {
var child = $('.artist');
var parentHeight = child.parent().height();
while( child.height() > parentHeight ) {
child.css('font-size', (parseInt(child.css('font-size')) - 1) + "px");
}
while( child.height() < parentHeight ) {
child.css('font-size', (parseInt(child.css('font-size')) + 1) + "px");
}
};
adjustFontSize(); // Call it when document is ready
window.onresize = adjustFontSize; // Call it each time window resizes
});
.artist-container {
width: 20%;
height: 40px;
border: 1px solid black;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="artist-container">
<div class="artist">Audhit Audhit Audhit Audhit Audhit Audhit Audhit</div>
</div><br>
<div class="artist-container">
<div class="artist">Lorem</div>
</div><br>
I think the CSS media queries approach is so much better for making a web responsive, than calculating everything with Javascript all the time.
For example, you can think about three sizes:
Phone (lets say, 400px width)
Tablet (lets say, 800px width)
Computer (lets say, >800px width)
One way of achieving this, using the desktop first approach, would be:
/* DESKTOP */
body {
font-size: 1em;
...
}
...
/* General rules for desktop
...
/* TABLET */
#media screen and (max-width:800px and min-width:400px) {
/* Overwrite the rules you want to change */
body {
font-size: .75em;
}
...
}
/* PHONE */
#media screen and (max-width:400px) {
/* Overwrite the rules you want to change */
body {
font-size: .75em;
}
#div1 {
height: 20%;
}
...
}
In addition to this, don't forget to work with relative units (em, vw, vh, rem...) and percentages.
Here you have a really good link about responsive design.

Resize positioned background image

I have span, and it's styles are represented below. My problem is, it was designed to fill 60px*60px span. But now, I have to make it to fill another span with 50px*50px size. But it can't work with background position, because if i change the background-size, all position slips away. So is there any way (css or javascript hack) to resize an image or a block element with bacground-image after the image has been drawn? I want to avoid rewriting all background positions (I've got classes for each icons like ".entertainment").
<span class="icon icon2 entertainment"></span>
span.icon2 {
float: left;
width: 50px;
height: 50px;
margin: 5px 0 0 0;
}
#wrapper span.icon.entertainment {
background-position: -60px -360px;
}
#wrapper span.icon {
background: url(https://teeg.hu/image/icon.png);
}
Thanks for any help!
There is no pure css solution.
There is a js solution. Resize the background (background-size) as you did, then for each element move the position with the difference between sizes / 2 (in your case 5px).
You don't rewrite the classes, just iterate through elements.
Note: This might become an extensive operation, it is better to rewrite classes, even though that is what you want to avoid (40 is not so much... at most 30 min - testing included).
Ok, I've written some hack. I resized the background:
background-size: 100px 1550px;
and did it with jQuery:
$(function() {
$("span.icon2").each(function(index, value) {
var pos = $(this).css("background-position").split(' ');
var newPos = [];
newPos[0] = parseInt(pos[0].replace("px", "")) / 60 * 50;
newPos[1] = parseInt(pos[1].replace("px", "")) / 60 * 50;
$(this).css("background-position", newPos[0] + "px " + newPos[1] + "px");
});
});

How to check in javascript that how much div settle as rows in wrapper?

The source is here http://jsfiddle.net/4fV3k/
I have a function SetGridBorder which take style of border like 1px solid red and selector of wrapper like box-wrapper.
As my example code 4 rows is lived in a row so their is 4 cols and 4 rows. How I can determine it in JavaScript. I want to set the border in this rules.
the 2 and 3 in first row have missing left and right border (so this is not duplicate border).
2nd and third column (middles rows) have missing top and bottom border so no duplicate border for here also.
How I can do it in JavaScript? Do someone have suggestion for how to do it better?
$(document).ready(function () {
var box_wrapper = $(".box-box-wrapper", ".box");
SetGridBorder(4,4)
});
function SetGridBorder(style,selector) {
}​
You can get how many rows and columns by divide wrapper width and height to box width and height. In your example wrapper height was zero, so i added overflow:auto; to body .box-wrapper class. Updated fiddle at http://jsfiddle.net/4fV3k/7/
function getRows() {
var wrapperWidth = $(".box-wrapper").width();
var boxWidth = $(".box-wrapper > div").width();
return Math.floor(wrapperWidth / boxWidth);
}
function getColumns() {
var wrapperHeight = $(".box-wrapper").height();
var boxHeight = $(".box-wrapper > div").height();
return Math.floor(wrapperHeight / boxHeight);
}
FYI.
body .box {
width: 128px;
height: 128px;
float: left;
text-align: center;
border:solid 1px #555;
}
$(document).ready(function () {
$.each($(".box"),function(i,n){
if((i+1)%4!=0){
$(n).css({'border-right':'none'})
}
if((i+1)>4){
$(n).css({'border-top':'none'})
}
});
});

Categories