SVG content get cropped for dynamic values - css

I have an color legend for discrete data, which is done using SVG. But I am getting issue to display the whole content as it is getting cropped. I cannot define fixed height since content are dynamic.
FYI: My code is written in react
Note: I can give overflow: visible and make the content visible but again then the issue comes in giving background color (background color wont get apply for overflowed content).
Code link: https://jsfiddle.net/rb4p9max/4/
React.useEffect(() => {
// calling legend function and passing div id to function
colorLegend("#legend");
}, [dep]);
function colorLegend(legend: string) {
// logic
select(legend)
.append("svg")
.attr("height", 100 + "%")
.attr("width", 100 + "%")
.style("background-color", "black")
.style("border-radius", "5px")
.call(colorLegend);
}
return (
<div style={{position: "absolute",right: 16,top: 10,backgroundColor:
"grey"}}>
<div id="legend"></div>
</div>
);

It's hard to answer it with just a small example from the react code. But, based on the fiddle you submitted, you could set a fixed height, but based on the number of legends you have. Something like:
height: calc(22px * 7 + (4px * 6));
Explaining the numbers:
22px * 7 is because every square is 22px height.
4px * 6 is accounting for the bottom margin. You don't need a bottom margin in the last one.
https://jsfiddle.net/gzebj1qn/
So, the final code would be something like:
height: calc(22px * ${legends.length} + (4px * ${legends.length -1}));

Related

How does a child scale font-size contingent on the parent? [duplicate]

This question already has answers here:
Font scaling based on size of container
(41 answers)
Closed 1 year ago.
I have a container that has a % width and height, so it scales depending on external factors. I would like the font inside the container to be a constant size relative to the size of containers. Is there any good way to do this using CSS? The font-size: x% would only scale the font according to the original font size (which would be 100%).
If you want to set the font-size as a percentage of the viewport width, use the vwunit:
#mydiv { font-size: 5vw; }
The other alternative is to use SVG embedded in the HTML. It will just be a few lines. The font-size attribute to the text element will be interpreted as "user units", for instance those the viewport is defined in terms of. So if you define viewport as 0 0 100 100, then a font-size of 1 will be one one-hundredth of the size of the svg element.
And no, there is no way to do this in CSS using calculations. The problem is that percentages used for font-size, including percentages inside a calculation, are interpreted in terms of the inherited font size, not the size of the container. CSS could use a unit called bw (box-width) for this purpose, so you could say div { font-size: 5bw; }, but I've never heard this proposed.
Another js alternative:
Working Example
fontsize = function () {
var fontSize = $("#container").width() * 0.10; // 10% of container width
$("#container h1").css('font-size', fontSize);
};
$(window).resize(fontsize);
$(document).ready(fontsize);
Or as stated in torazaburo's answer you could use svg. I put together a simple example as a proof of concept:
SVG Example
<div id="container">
<svg width="100%" height="100%" viewBox="0 0 13 15">
<text x="0" y="13">X</text>
</svg>
</div>
You may be able to do this with CSS3 using calculations, however it would most likely be safer to use JavaScript.
Here is an example: http://jsfiddle.net/8TrTU/
Using JS you can change the height of the text, then simply bind this same calculation to a resize event, during resize so it scales while the user is making adjustments, or however you are allowing resizing of your elements.
I used Fittext on some of my projects and it looks like a good solution to a problem like this.
FitText makes font-sizes flexible. Use this plugin on your fluid or responsive layout to achieve scalable headlines that fill the width of a parent element.
It cannot be accomplished with css font-size
Assuming that "external factors" you are referring to could be picked up by media queries, you could use them - adjustments will likely have to be limited to a set of predefined sizes.
Here is the function:
document.body.setScaledFont = function(f) {
var s = this.offsetWidth, fs = s * f;
this.style.fontSize = fs + '%';
return this
};
Then convert all your documents child element font sizes to em's or %.
Then add something like this to your code to set the base font size.
document.body.setScaledFont(0.35);
window.onresize = function() {
document.body.setScaledFont(0.35);
}
http://jsfiddle.net/0tpvccjt/
I had a similar issue but I had to consider other issues that #apaul34208 example did not tackle. In my case;
I have a container that changed size depending on the viewport using media queries
Text inside is dynamically generated
I want to scale up as well as down
Not the most elegant of examples but it does the trick for me. Consider using throttling the window resize (https://lodash.com/)
var TextFit = function(){
var container = $('.container');
container.each(function(){
var container_width = $(this).width(),
width_offset = parseInt($(this).data('width-offset')),
font_container = $(this).find('.font-container');
if ( width_offset > 0 ) {
container_width -= width_offset;
}
font_container.each(function(){
var font_container_width = $(this).width(),
font_size = parseFloat( $(this).css('font-size') );
var diff = Math.max(container_width, font_container_width) - Math.min(container_width, font_container_width);
var diff_percentage = Math.round( ( diff / Math.max(container_width, font_container_width) ) * 100 );
if (diff_percentage !== 0){
if ( container_width > font_container_width ) {
new_font_size = font_size + Math.round( ( font_size / 100 ) * diff_percentage );
} else if ( container_width < font_container_width ) {
new_font_size = font_size - Math.round( ( font_size / 100 ) * diff_percentage );
}
}
$(this).css('font-size', new_font_size + 'px');
});
});
}
$(function(){
TextFit();
$(window).resize(function(){
TextFit();
});
});
.container {
width:341px;
height:341px;
background-color:#000;
padding:20px;
}
.font-container {
font-size:131px;
text-align:center;
color:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container" data-width-offset="10">
<span class="font-container">£5000</span>
</div>
https://jsfiddle.net/Merch80/b8hoctfb/7/
I've given a more detailed answer of using vw with respect to specific container sizing in this answer, so I won't just repeat my answer here.
In summary, however, it is essentially a matter of factoring (or controlling) what the container size is going to be with respect to viewport, and then working out the proper vw sizing based on that for the container, taking mind of what needs to happen if something is dynamically resized.
So if you wanted a 5vw size at a container at 100% of the viewport width, then one at 75% of the viewport width you would probably want to be (5vw * .75) = 3.75vw.
If you want to scale it depending on the element width, you can use this web component:
https://github.com/pomber/full-width-text
Check the demo here:
https://pomber.github.io/full-width-text/
The usage is like this:
<full-width-text>Lorem Ipsum</full-width-text>
You can also try this pure CSS method:
font-size: calc(100% - 0.3em);

How to override position of primefaces OneMenu?

How to override primefaces OneMenu in order to see it over captcha, ie below? My selectOneMenu have no any changes.
My guess is that the menu panel doesn't have enough space to fit in the lower part, instead it's positioned above, as the aligning of the panel is being set by javascript (PrimeFaces.widget.SelectOneMenu.alignPanel), using the jQuery UI .position() method which allows you to position an element relative to the window, document, another element, or the cursor/mouse, without worrying about offset parents, and the default value for collision attribute is flip (In PrimeFaces 5 it's flipfit) resulting the positioned element overflows the window in some direction, or to move it to an alternative position.
In this case you could implement one of these three solutions:
extend the space on the lower part, maybe adding margin to the
captcha, in this way the panel would fit in bottom.
OR change the hight of the panel
<p:selectOneMenu height="100" >
Making it a bit shorter so it can fit.
OR you can override the PrimeFaces.widget.SelectOneMenu.alignPanel function
to set the collision attribute to none, in the position function:
PrimeFaces 5
PrimeFaces.widget.SelectOneMenu.prototype.alignPanel = function() {
if(this.panel.parent().is(this.jq)) {
this.panel.css({
left: 0,
top: this.jq.innerHeight()
});
}
else {
this.panel.css({left:'', top:''}).position({
my: 'left top'
,at: 'left bottom'
,of: this.jq
,collision: 'none' // changing from flipfit to none
});
}
}
PrimeFaces 4
PrimeFaces.widget.SelectOneMenu.prototype.alignPanel = function() {
var fixedPosition = this.panel.css('position') == 'fixed',
win = $(window),
positionOffset = fixedPosition ? '-' + win.scrollLeft() + ' -' + win.scrollTop() : null;
this.panel.css({left:'', top:''}).position({
my: 'left top'
,at: 'left bottom'
,of: this.jq
,offset : positionOffset
,collision: 'none' // changing from default flip to none
});
}
Of course you should call it in the document.ready, and when you update the component.
I don't recommend this approach too much, but sometimes it's the only solution.
Hope this helps.
For necessary SelectOneMenu add style top find an optimal value and apply it. For me it is:
#registrationForm\:facultyList_panel {
top: 413px !important;
}
UPDATE 09.07: It does not helps for another screen resolution. The question is still relevant.

Floating with css percentages, full-width browsing

Original question:
Okay, this is plain and simple css. But there's a bug on my site and i can't get it out !
I making a site with this design: http://cl.ly/image/1j231y2x3w07
The site i fully responsive and makes use of the css-aspect-ratio-technique:
HTML:
<div class="post small">Post that is small</div>
<div class="post big">Post that is big</div>
<div class="post tall">Post that is tall</div>
<div class="post wide">Post that is wide</div>
CSS/LESS:
.post {position: relative;}
.post:after {display: block; content: '';}
.post.small {width: calc(1/4 * 100%);}
.post.small:after {padding-top: 70%;}
.post.big {width: calc(1/2 * 100%);}
.post.big:after {padding-top: 70%;}
.post.tall {width: calc(1/4 * 100%);}
.post.tall:after {padding-top: 140%;}
.post.wide {width: calc(1/2 * 100%);}
.post.wide:after {padding-top: 35%;}
You get the gist of it.
I also make use of the excellent plugin Packery.js to keep track of floats and position. I mostly use is as a resize and animation helper.
But being fully responsive gives me a problem. For example when the browser window is 1304px wide, i get some odd height values(ex. 477.4px) due to the technique mentioned above. Because of the odd numbers i am not able to keep my grid, let alone my design.
And if the windows width is not divisible by 4 i get overlapping or 1 pixel white lines.
I've been working on this for quite some time now, and need some fresh eyes.
So, if anybody got inputs to a solution i would be very happy. Thanks :-)
The solution:
A big thanks to #ScottS – great advice !
function frontpageResize() {
// container ... duh.
var container = $('#frontpage-wrapper');
// body width.
var bWidth = window.innerWidth;
// get the pixels missing for making bWidth divisible by 20.
var divisibleBy = bWidth % 20;
// setting an alternative width.
var altWidth = Math.ceil(bWidth - divisibleBy + 20);
// what's missing?
var leftover = altWidth - bWidth;
// if body width is divisible by 20 all is peaches?
if(divisibleBy === 0) {
container.width(bWidth);
} else {
// else set the alternative width as body width and set margin-left.
container.width(altWidth).css({ "margin-left" : -leftover / 2 + "px"});
}
// relayout Packery.js
container.packery();
}
The Only Way You Will Eliminate All Rounding Issues
To get the quartering division of width's without issues, as you noted, you need a total width that is divisible by 4. To get the height divisions with the percentages you are using you need a total width that is divisible by 20 (35% of 20 = 7, a prime number; there is no other values between 1-19 that can be multiplied by 35% without a fraction being generated).
So that means you need your widths to not shoot for 100% window width, but rather the width value that is the next smallest division by 20 (and then perhaps center your display, so that the 0 to 9.5px left over become side margins through an margin: 0 auto rule).
So your theoretical calculation you need for your width value needs to use a modulus function, something like this:
#width - mod(#width, 20) //in LESS
or
width - (width%20) //in javascript
As you can see, though, the point is you would need a dynamic action that CSS does not have available natively to make it pixel perfect.

Twitter Bootstrap - Giving thumbnail caption a minimum number of lines

I have a carousel in Bootstrap that displays 4 columns of thumbnails. Here's the carousel in question. If you move to the third page, you can see that the container increases in height in order to accommodate the contents of the thumbnail captions. I've been trying many things such as setting bottom margins, min heights, etc. to get the position of the "View Details" button constant across the entire carousel.
My question is what is the best way to approach this issue? I was thinking somehow making the thumbnail caption height a minimum of 4 or so lines, but I tried that(probably the wrong way) to no avail.
When I add
.caption h4 {
min-height: 2.2em; /* 2 lines as line-height is 1.1 */
}
I get all "View details" at the same level. However, that obviously doesn't treat the problem of captions being even higher. It only works if no caption is higher in fact. (But it IS ok, if you know for sure nothing is going to be higher than your multiple.)
So, instead I apply this little bit of CSS to put a limit from the other side.
.caption h4 {
max-height: 4.4em; /* 4 lines as line-height is 1.1 */
height: 4.4em; /* making it a multiple allows usage of overflow */
overflow: hidden; /* without cutting a line in the middle */
}
If you want to set a max-height equal to the height of the highest of captions dynamically, than you would have to use a little bit of JS:
(function(d) {
var captions = d.querySelectorAll('.caption h4'),
height = 0;
for(var i = 0; i < captions.length; i++) {
height = Math.max(height, captions[i].offsetHeight); // or clientHeight depends on you box model
}
var style = d.createElement('style');
style.type = 'text/css';
style.innerHTML = '.caption h4 { max-height: '+ height +'px; height: '+ height +'px; }'; // they don't need overflow as none of them can overflow;
d.getElementsByTagName('head')[0].appendChild(style);
})(document);
You add this script at the end of body, so that the DOM is already loaded (or somehow trigger it onload).
Important: this snippet is not supported by older browsers because of the querySelectorAll.
And that does the trick when I run it on your site.

How can I autoscale the font size to fit the contents of a div?

I have a div with some text:
<div style="white-space:nowrap;overflow:none;width:50px;">
With some text in it
</div>
How can I scale the font size of the text so all of the text is visible?
Contrary-wise. You could wrap the text in an interior DIV, measure its width with JavaScript. Test if that width is wider than the parent DIV. Get the current font size, and incrementally move it down 1px at a time until inner DIV's width is less than or equal to the outer DIV's width.
I've been doing something like this, to set the text scale relative to the parent (or window) width / height. You can avoid jQuery by using offsetWidth and offsetHeight instead of width.
var setBodyScale = function () {
var scaleSource = $(window).width(), // could be any div
scaleFactor = 0.055,
maxScale = 500,
minScale = 75; //Tweak these values to taste
var fontSize = (scaleSource * scaleFactor) - 8; //Multiply the width of the body by the scaling factor:
if (fontSize > maxScale) fontSize = maxScale;
if (fontSize < minScale) fontSize = minScale; //Enforce the minimum and maximums
$('html').css('font-size', fontSize + '%'); // or em
}
Short Answer: You don't.
You would have to try a size, render it, see if it fits, try another size, render it see if it fits, etc. Then you have to handle the case where the calculated font size is so small no one can read the text.
There are other options, if the text doesn't fit, add an ellipsis (...) to the end of the text, when you mouse over it, the div could expand, you could use a popup window or tooltip with the full text, or put the full text in a larger area of the screen.
Find another way.
Came across this JQuery plugin in my quest to find the same.
Github
Demo
Also came across this Jquery script when I was looking for the same thing. It has the added benefit over the others, as far as I quickly tell, is that it also adjusts for height as well as width.
Comes from here: http://www.metaltoad.com/blog/resizing-text-fit-container
function adjustHeights(elem) {
var fontstep = 2;
if ($(elem).height()>$(elem).parent().height() || $(elem).width()>$(elem).parent().width()) {
$(elem).css('font-size',(($(elem).css('font-size').substr(0,2)-fontstep)) + 'px').css('line-height',(($(elem).css('font-size').substr(0,2))) + 'px');
adjustHeights(elem);
}
}

Resources