How to dynamically remove space around text? - css

I would like to be able to remove the "space" at the top and the bottom of a text inside of a container.
The div must be as close as possible to the text inside.
This text is the result of a input and can be changed by the user.
I guess that I should work with the line-height, but how?
Any advice would be greatly appreciated!

Used to line-height
.some_css{
line-height: px; // according to your text size of design
}

Use the CSS padding property to set space within the borders of the element:
padding:0;
Additionally as Terric has pointed out, if the child has a margin, remove it:
margin:0;

you can either use padding: 0' or try line-height:px
what padding do
with zero padding
and line height

As explained in the title, I needed to "dynamically" remove the space around text.
In fact, every fonts have different structure and don't render in the same way on every browser...
I found a compromise for this :
.text { line-height: 70% }
As explained here, if we use a percentage, we could apply any font-size to our text, the line-height will always be the same.
I can change the font-size with jQuery, the line-height will always be properly applied to the text and to the surrounding element.
I dealt with a case function for every font to apply a different line-height. In my case, this is a working solution...
var fontFamily = $( "input" ).val(); // Here, the font-Size is defined dynamically by the user... It could be Arial, Verdana, Comic etc...
var lineHeight;
switch ( fontFamily ){
case "Arial Black": // if the user has selected the arial black font...
lineHeight = "70%"; // we define a line-height that will be correctly applied to the text
break;
case "Verdana":
lineHeight = "78%";
break;
default:
lineHeight = "66%";
}
$( ".text" ).css("line-height", lineHeight); // we apply the line-height to the text...
Note that the user can also change the font-size with another select element...
Hope this could help...

Related

display input text as span, width trouble

I'm trying to make an input text look like exactly like a span. I want my user to be able to type text without noticing he's in a field.
I've almost succeeded, the last problem I've got is about the width of the input.
The input text is wider than the text it's replacing.
Here's the jsfiddle. (You may click on "Texte" to type yours).
Here's the interesting css part :
input {
background-color: transparent;
padding: 0px;
border: initial;
font: inherit;
margin: 0px;
}
Here is the idea try fixed width for the inputs
Demo : http://jsfiddle.net/nyitsol/eotd8p4n/17/
also you may try use the same width of the span for the input
$('span.width').width(); // returns a width value
using this get the width of the span and put it into the input box using JavaScript.
EDIT:
try this, if you want to grow the input based on text limit then you have to increase the size as well.
http://jsfiddle.net/nyitsol/eotd8p4n/25/
var input = $('<input onkeypress=\"this.style.width = ((this.value.length + 1) * 8) + \'px\';\" type=text>');

Wrap text from bottom to top

Anybody know how I could wrap the text in reverse order, from bottom to top?
I attached an example image.
[][http://i.stack.imgur.com/RVsIG.jpg]
Instead of breaking the line after it is full and having an incomplete line at the end, I need to brake somehow from bottom to top, so bottom lines are full and top line is incomplete.
I would not recommend using exotic CSS attributes which aren't even in Chrome & Firefox yet. The best cross-browser solution is to handle this in Javascript when the document loads. Here's a sketch of how to do that:
$(function() {
$(".title").each(function(i,title) {
var width = 0;
var originalHeight = $(title).height();
var spacer = $('<div style="float:right;height:1px;"/>').prependTo(title);
while (originalHeight == $(title).height()) {
spacer.width( ++width );
}
spacer.width( --width );
});
});
Working JSFiddle is here: http://jsfiddle.net/zephod/hfuu3m49/1/
6 years later, but fret not! I have found a pure CSS solution!
Turns out you can achieve this result with flexbox, but it's not obvious or very straight forward. This is what I started out with:
I want the header to be "bottom-heavy", the same effect as you describe in the question.
I began by splitting up my string by whitespace and giving them each a <span> parent. By using flex-wrap: wrap-reverse, and align-content: flex-start. You will achieve this:
Oh no! Now the order is messed up! Here comes the trick. By reversing both the order in which you add spans to the HTML and the direction order of flex with 'flex-direction: row-reverse', you actually achieve the "pyramid-shaped" upwards overflow effect you desire.
Here is my (simplified) code, using react and react-bootstrap:
<Row className='d-flex flex-wrap-reverse flex-row-reverse align-content-start'>
{props.deck.name
.split(' ')
.reverse()
.map(word => (
<span className='mr-1'>{word}</span>
))}
</Row>
There is no general css solution for it. You must have to utilize help of any language.
This is one of the solution using PHP:
<?php
$str= "This is what I want to achieve with your help";
$str = strrev($str);
$exp = str_split($str,18);
$str = implode(">rb<", $exp);
echo strrev($str);
?>
Well, if that is depending on the text, then you can try something like a word replacer. For example
var words = "This is what I want to achieve";
var newWords.replace("what", "what <br />"); // note the line break
document.write(newWords);
Here is a fiddle for you: http://jsfiddle.net/afzaal_ahmad_zeeshan/Ume85/
Otherwise, I don't think you can break a line depending on number of characters in a line.
Wrap and Nowrap will be rendered by the client-browser, so you can not force the browser to wrap from bottom to top. but you can do that with javascript or asp.
This is not a formal solution for this problem. But see if this helps.
The HTML CODE
<div id="mydiv">
I can imagine the logic behind the code having to detect what is the last line, detect the div size, and the font size... then measure how many characters it can fit and finally go to the above line and insert the break where necessary. Some font families might make this harder, but trial and error should solve the issue once the basic code is set..
</div>
CSS:
#mydiv
{
width:1000px;
line-height:18px;
font-size:20px;
text-align:justify;
word-break:break-all;
}
Here setting the div width around 50 times that of the font-size will give you the precise result. Other width values or font values might slightly disorient the last line, giving some blank space after the last character.(Could not solve that part, yet).
JQuery:
$(document).ready(function(){
//GET the total height of the element
var height = $('#mydiv').outerHeight();
//Get the height of each line, which is set in CSS
var lineheight = $('#mydiv').css('line-height');
//Divide The total height by line height to get the no of lines.
var globalHeight = parseInt(height)/parseInt(lineheight);
var myContent = $('#mydiv').html();
var quotient = 0;
//As long as no of lines does not increase, keep looping.
while(quotient<=globalHeight)
{
//Add tiny single blank space to the div's beginning
$('#mydiv').html(' '+myContent);
//Get the new height of line and height of div and get the new no of lines and loop again.
height = $('#mydiv').outerHeight();
lineheight = $('#mydiv').css('line-height');
quotient = parseInt(height)/parseInt(lineheight);
myContent = $('#mydiv').html();
}
//get the final div content after exiting the loop.
var myString = $('#mydiv').html();
//This is to remove the extra space, which will put the last chars to a new line.
var newString = myString.substr(1);
$('#mydiv').html(newString);
});
If you already know where you want your breaks to take place just use simple HTML breaks to break your content and have it display the way you want.
<p>This is what<br/>
want to acheive with your help</p>
If you set the breaks manually (and you know where you want them to break) then create them yourself.
You could also try setting separate css width adjustments based on the dimensions of the screen you are seeing the breaking you are not liking and set an #media reference to make the div width smaller to break the text so it doesn't run unevenly across the top of certain size devices.
Use display: inline-block; on the text div.

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.

Adjust size based on height (vertical length)

I am doing a div that needs to display the whole content of a text field and adjust the text size dynamically so that it will not overflow.
To get an idea of the problem, look here http://sandbox.littlegraffyx.com/bible/
You can try entering verses at lower left text box using the format GEN 1:1 for "Genesis 1:1"
My problem is when I try to display long verses, they get truncated. I need to change the size based on how long the current text is. Is there some css that can be applied based on text field size?
As mentioned in the comments, it isn't possible to scale text based on the height of its containing element using pure CSS. But here's a small jQuery script I have used in the past when I needed to achieve what you want. It also adjusts the text size when the user resizes the browser window.
HTML:
<p class="quote">
Really long text goes here...
</p>​
CSS:
.quote {
// The largest size to display text at.
font-size: 36px;
}​
JS:
$(window).bind('resize',function(e){
scaleQuote();
});
function scaleQuote(){
var quote = $('.quote');
var winH = $(window).height();
// Reset font size.
quote.css('font-size', '');
// If quote is larger than viewport, reduce font-size until it fits.
while (winH < (quote.height())){
var fontSize = parseInt(quote.css('font-size'), 10);
quote.css('font-size', fontSize-1+'px');
}
}
scaleQuote();​
Demo: http://jsfiddle.net/eCBmc/2/
You can try something like this. It will set input field to 10 character, and if it's bigger it increase it's size.
http://jsfiddle.net/4qjjf/1/
<html>
<body>
<textarea cols="10" rows="1" id="shit"
onkeyup="this.cols=this.value.length>10?this.value.length:10;"></textarea>
</body>
</html>​

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