I need to use a textarea to show some text. The problem is that if I place 4-5 rows of text a scrollbar will appear. How can I use CSS/HTML so that the textarea will be as large as it's content (no scrollbar).
the textarea doesn't need to change it's size dynamicaly, I use it only to show a text (I could also use a disabled textarea)
I want the textarea to stretch only verticaly.
If you want to know:
I use the textarea to show some text from a database, so when the textarea (with the text in it) is created, it should show the whole text at once with no scrollbars.
<!DOCTYPE html>
<html>
<head>
<title>autoresizing textarea</title>
<style type="text/css">
textarea {
border: 0 none white;
overflow-y: auto;
padding: 0;
outline: none;
background-color: #D0D0D0;
resize: none;
}
</style>
<script type="text/javascript">
var observe;
if (window.attachEvent) {
observe = function (element, event, handler) {
element.attachEvent('on'+event, handler);
};
}
else {
observe = function (element, event, handler) {
element.addEventListener(event, handler, false);
};
}
function init (maxH) {
var text = document.getElementById('text');
var maxHeight=maxH;
var oldHeight= text.scrollHeight;
var newHeight;
function resize () {
text.style.height = 'auto';
newHeight= text.scrollHeight;
if(newHeight>oldHeight && newHeight>maxHeight )
{
text.style.height=oldHeight+'px';
}
else{
text.style.height = newHeight+'px';
oldHeight= text.scrollHeight;
}
}
/* 0-timeout to get the already changed text */
function delayedResize () {
window.setTimeout(resize, 0);
}
observe(text, 'change', resize);
observe(text, 'cut', delayedResize);
observe(text, 'paste', delayedResize);
observe(text, 'drop', delayedResize);
observe(text, 'keydown', delayedResize);
text.focus();
text.select();
resize();
}
</script>
</head>
<body onload="init(200);">
<textarea rows="1" style="height:1em;" id="text"></textarea>
</body>
</html>
http://jsfiddle.net/TDAcr/
I´m afraid you´ll have to resort to javascript to set the height of your textarea. You can use the scrollHeight property to determine the total height.
Alternatively you could just use a div and style the div to look like a textarea. The div will grow automatically and as it´s a disabled textarea anyway, you don´t really need it to be a textarea.
Alright, I just found this and it works very nicely:
<html>
<head>
<script>
function textAreaAdjust(o) {
o.style.height = "1px";
o.style.height = (25+o.scrollHeight)+"px";
}
</script>
</head>
<body>
<textarea onkeyup="textAreaAdjust(this)" style="overflow:hidden"></textarea>
</body>
</html>
Now, I shouldn't assume that you know Javascript (but you might).
Just run
textAreaAdjust(document.getElementById("id of your text area"))
Something like that should work. I'm not the best with Javascript (not even close, I just started using it the other day)
That seems to do something similar to what you want. The first code example is for a textarea that dynamically changes based on what is in it (while typing). It will take a couple of changes to get it how you want.
You could use the CSS height: and width: attributes, e. g. something like
<textarea style="width:400px;height:300px">...</textarea>, just use the sizes you want to.
In addition, if you want to suppress the scrollbar, use overflow:hidden.
you can use div like textarea. It is possible like this:
<div contenteditable="true" style="width:250px; border:1px solid #777" ></div
Find the height of the font you will most likely be displaying it in. I'm not sure about CSS/HTML but you could use Javascript/PHP/ASP.net to use map to determine how big the text will be based on the number of characters. If you do it in a monospaced font, this will be even easier. Why use a text area when you could just use a label which will do the same thing all by itself?
If you don't mind using JavaScript you can use approach from one of following articles:
http://james.padolsey.com/javascript/jquery-plugin-autoresize/
http://scvinodkumar.wordpress.com/2009/05/28/auto-grow-textarea-doing-it-the-easy-way-in-javascript/
But from your questing I assume you want pure CSS solution.
Then you can just mimic appereance of textarea using simple div and following css (if you just want to display text):
div {
cursor: text;
background: lightGray;
border: 1px solid gray;
font-family: monospace;
padding: 2px 0px 0px 2px;
}
I assume name attribute is not used. You can use this alternative (HTML5):
http://jsfiddle.net/JeaffreyGilbert/T3eke/
Using the resize property works these days:
resize: none;
Related
so Iv'e made an input that it's height is "300px" what means that its pretty big, and when I type a text the input it's starts from the middle of the input and not from the left top. How do I do it?
text-align: left;
height: 300px;
You could use padding instead of height.
Something along the lines of this would suffice:
input{
padding-bottom: 280px; /* change this depending on your requirements */
}
Although I don't recommended this. It's very tacky and un-user friendly. As the comments suggested, you should have a look into HTML's native textarea element.
This may not be what you were looking for but consider it.
var textarea = document.getElementById("demo");
function getValue() {
alert(textarea.value); // Works just like a text input!!!
}
#demo {
height: 300px;
resize: horizontal;
/* Considering you have defined a height */
}
<!DOCTYPE html>
<html>
<head>
<!--
<link rel="stylesheet" href="path/to-your/css-file.css">
-->
</head>
<body>
<textarea id="demo">And yes you can get the value of a textarea just like a text input!</textarea>
<button onclick="getValue()">Get Value</button>
</body>
</html>
Following is my HTML
Branding
Is it possible to access using CSS to access anchor tag's text?
Something like this is what I want? The html is dynamically generated, so please don't mention to have id's or to have any classes.
a[text='Branding']
{
}
People already told you that you CAN'T select text in CSS. But there's some workaround in my opinion.
I don't know what you want to do, possibly a bad thing, but if I were you I'd take this bad practice:
/*First you hide the text*/
a {
font-size: 0; /* hide text */
text-decoration: none !important; /* get rid of that awful underline */
}
/* then you insert a new element using :before */
a:before {
content: 'Branding'; /* This is the text you want for the new element */
color: #333;
font-size: 15px; /* Bring back the text inside the anchor for this new element */
font: 24px sans-serif;
}
fiddle: http://jsfiddle.net/tsu7z546/
In case you want to try out jQuery:
$(document).ready(function(){
var brandingAnchor = $('a:contains("Branding")');
brandingAnchor.hide();
});
Remember! Every time you write jQuery code, you must have already called jQuery library on your page, just like this:
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
</body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
//Your jQuery code goes HERE, just below the library
$(document).ready(function(){
var brandingAnchor = $('a:contains("Branding")');
brandingAnchor.hide();
});
</script>
Is there a method in html which makes the webpage scroll to a specific Element using HTML !?
Yes you use this
<div id="google"></div>
But this does not create a smooth scroll just so you know.
You can also add in your CSS
html {
scroll-behavior: smooth;
}
You should mention whether you want it to smoothly scroll or simply jump to an element.
Jumping is easy & can be done just with HTML or Javascript. The simplest is to use anchor's. The limitation is that every element you want to scroll to has to have an id. A side effect is that #theID will be appended to the URL
Go to Title
<div>
<h1 id="scroll">Title</h1>
</div>
You can add CSS effects to the target when the link is clicked with the CSS :target selector.
With some basic JS you can do more, namely the method scrollIntoView(). Your elements don't need an id, though it is still easier, e.g.
function onLinkClick() {
document.getElementsByTagName('h2')[3].scrollIntoView();
// will scroll to 4th h3 element
}
Finally, if you need smooth scrolling, you should have a look at JS Smooth Scroll or this snippet for jQuery. (NB: there are probably many more).
<!-- HTML -->
<div id="google"></div>
/*CSS*/
html { scroll-behavior: smooth; }
Additionally, you can add html { scroll-behavior: smooth; } to your CSS to create a smooth scroll.
Year 2020. Now we have element.scrollIntoView() method to scroll to specific element.
HTML
<div id="my_element">
</div>
JS
var my_element = document.getElementById("my_element");
my_element.scrollIntoView({
behavior: "smooth",
block: "start",
inline: "nearest"
});
Good thing is we can initiate this from any onclick/event and need not be limited to tag.
If you use Jquery you can add this to your javascript:
$('.smooth-goto').on('click', function() {
$('html, body').animate({scrollTop: $(this.hash).offset().top - 50}, 1000);
return false;
});
Also, don't forget to add this class to your a tag too like this:
Text
Here is a pure HTML and CSS method :)
html {
scroll-behavior: smooth;
/*Adds smooth scrolling instead of snapping to element*/
}
#element {
height: 100px;
width: 100%;
background-color: red;
scroll-margin-block-start: 110px;
/*Adds margin to the top of the viewport*/
scroll-margin-block-end: 110pxx;
/*Adds margin to the bottom of the viewport*/
}
#otherElement {
padding-top: 500px;
width: 100%;
}
Link
<div id="otherElement">Content</a>
<div id="element">
Where you want to scroll
</div>
<div id="otherElement">Content</a>
<nav>
1
2
3
</nav>
<section id="section1">1</section>
<section id="section2" class="fifty">2</section>
<section id="section3">3</section>
<style>
* {padding: 0; margin: 0;}
nav {
background: black;
position: fixed;
}
a {
color: #fff;
display: inline-block;
padding: 0 1em;
height: 50px;
}
section {
background: red;
height: 100vh;
text-align: center;
font-size: 5em;
}
html {
scroll-behavior: smooth;
}
#section1{
background-color:green;
}
#section3{
background-color:yellow;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" >
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});
</script>
I got it working by doing this, consider that top-page is the element that you want to scroll to:
document.getElementById("top-page").scrollTo({ behavior: "smooth", top: 0 });
Yes, you may use an anchor by specifying the id attribute of an element and then linking to it with a hash.
For example (taken from the W3 specification):
You may read more about this in Section Two.
...later in the document
<H2 id="section2">Section Two</H2>
...later in the document
<P>Please refer to Section Two above
for more details.
By using an href attribute inside an anchor tag you can scroll the page to a specific element using a # in front of the elements id name.
Also, here is some jQuery/JS that will accomplish putting variables into a div.
<html>
<body>
Click here to scroll to the myContent section.
<div id="myContent">
...
</div>
<script>
var myClassName = "foo";
$(function() {
$("#myContent").addClass(myClassName);
});
</script>
</body>
Should you want to resort to using a plug-in, malihu-custom-scrollbar-plugin, could do the job. It performs an actual scroll, not just a jump. You can even specify the speed/momentum of scroll. It also lets you set up a menu (list of links to scroll to), which have their CSS changed based on whether the anchors-to-scroll-to are in viewport, and other useful features.
There are demo on the author's site and let our company site serve as a real-world example too.
The above answers are good and correct. However, the code may not give the expected results. Allow me to add something to explain why this is very important.
It is true that adding the scroll-behavior: smooth to the html element allows smooth scrolling for the whole page. However not all web browsers support smooth scrolling using HTML.
So if you want to create a website accessible to all user, regardless of their web browsers, it is highly recommended to use JavaScript or a JavaScript library such as jQuery, to create a solution that will work for all browsers.
Otherwise, some users may not enjoy the smooth scrolling of your website / platform.
I can give a simpler example on how it can be applicable.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
</script>
<style>
#section1 {
height: 600px;
background-color: pink;
}
#section2 {
height: 600px;
background-color: yellow;
}
</style>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Smooth Scroll</h1>
<div class="main" id="section1">
<h2>Section 1</h2>
<p>Click on the link to see the "smooth" scrolling effect.</p>
Click Me to Smooth Scroll to Section 2 Below
<p>Note: Remove the scroll-behavior property to remove smooth scrolling.</p>
</div>
<div class="main" id="section2">
<h2>Section 2</h2>
Click Me to Smooth Scroll to Section 1 Above
</div>
</body>
</html>
Is it possible with CSS/HTML to resize some box to match exactly it's background image size? Without using javascript.
For instance let's say I have a simplest div:
<div class="image">TEST</div>
.image {
background-image: url(http://placehold.it/350x150);
width: 350px;
height: 150px;
}
And I would like to resize it to those 350x150 dimensions without hardcoding those values. Also I cannot put any content inside this div.
http://jsfiddle.net/5Dane/
EDIT: I see a lot of answers I already was aware of, thank you for them, but that's not the solution here unfortunately. Below I'm explaining why I need such functionality.
What I'm trying to do is a form with steps (buttons previous and next). In session I hold all the values the user has input but there are some buttons which will add more functionality for the user (like multiple dynamically added rows for data). I'm doing it with jQuery of course, but I want the form to be able to work when there is no java script enabled.
Now to the point - I was trying to find out how to tell the difference which button the user has clicked. The case is all my submit buttons need to be images and the simplest solution <input type="image"/> doesn't send info about the button clicked with POST data. That's why I came to this solution:
<input class="submit_img" type="submit" style="background-image:url(http://placehold.it/108x23); width:108px; height: 23px;" value=" " name="some" />
/* Submit button with image */
input.submit_img {
font-size: 1em;
border-radius: 0px;
box-shadow: rgba(0, 0, 0, 0.15) 0 1px 1px;
border: solid 0px #000000;
cursor: pointer;
}
http://jsfiddle.net/XRvqV/
This way my form will submit all the data AND I will know which button the user clicked. Also the button looks fine, like it should look. I was wondering though if it was possible to make it a little more portable - my buttons all have different widths for different functions. Can someone suggest another approach here?
No, you can't. CSS is not aware of the the image size. You can do it easily with JQuery.
JQuery exmaple
$(function(){
var bg = $("div.image").css('background-image');
bg = bg.replace('url(','').replace(')','');
var newImg = new Image();
newImg.src = bg;
$("div.image").css("width",newImg.width);
$("div.image").css("height",newImg.height);
});
This is a hack and doesn't use background-image (uses an img tag instead), but is the only way I can think of without using JS.
HTML
<div class="container">
<div class="image">
<img src="http://www.pandafix.com/pandafix/images/untitled_1.jpg"/>
</div>
<div class="content">
some text
<br/>
some more text
<br/><br/><br/><br/>
text text text
</div>
</div>
CSS
.container {
position: relative;
}
.content {
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
color: red;
}
Basically, you allow an img tag to determine the height and width of a container. Then, overlay whatever content you want on top of the image (I'm assuming you want to put something on top).
jsFiddle
i would suggest you a alternative way to solve your problem. if you use bootstrap you can involve a div to make resizable image.
<div class="img-responsive">
<img src="test.jpg" width='xxx' height='yyy' alt='test'>
</div>
You can't do that using just HTML. But you can do this using HTML!
You should try this:
background-size: values;
This way, you will resize the background-image to the size of the container!
You can't do it directly.
The only solution it would be fetching the BG of the DIV element and attach new DOM img element to the DOM node, afterwards you could use the info of the image to add the proper with and height..
if you are willing to use jquery you can do this.
$(function(){
$('.image').each(function(index,element){
var _t = $(this);
_t.data("LinkedImg","LinkedImage"+index);
$('body').append(
$('<img />',{
id:"LinkedImage"+index,
src:_t.css('background-image')
}).hide());
});
$('document').on('load',function(){
$('.image').each(function(index,element){
var _t = $(this);
var _tmp_img = $('#'+ _t.data("LinkedImg"));
_t.css({
width:_tmp_img.width(),
height: _tmp_img.height()
});
});
});
})
Is there a freely available jQuery plugin that changes placeholder behavior to match HTML5 spec?
Before Focus
On Focus Good (Safari)
On Focus Bad (Chrome, Firefox)
You can what your browser does with this simple fiddle.
HTML5 draft spec says:
User agents should present this hint to the user, after having stripped line breaks from it, when the element's value is the empty string and/or the control is not focused (e.g. by displaying it inside a blank unfocused control and hiding it otherwise).
The "/or" is new in current draft so I suppose that's why Chrome and Firefox don't support it yet. See WebKit bug #73629, Chromium bug #103025.
Stefano J. Attardi wrote a nice jQuery plugin that just does that.
It is more stable than Robert's and also fades to a lighter grey when the field gets focused.
See the demo page
Grab it on GitHub
Play with the fiddle
I modified his plugin to read placeholder attribute as opposed to manually creating a span.
This fiddle has complete code:
HTML
<input type="text" placeholder="Hello, world!">
JS
// Original code by Stefano J. Attardi, MIT license
(function($) {
function toggleLabel() {
var input = $(this);
if (!input.parent().hasClass('placeholder')) {
var label = $('<label>').addClass('placeholder');
input.wrap(label);
var span = $('<span>');
span.text(input.attr('placeholder'))
input.removeAttr('placeholder');
span.insertBefore(input);
}
setTimeout(function() {
var def = input.attr('title');
if (!input.val() || (input.val() == def)) {
input.prev('span').css('visibility', '');
if (def) {
var dummy = $('<label></label>').text(def).css('visibility','hidden').appendTo('body');
input.prev('span').css('margin-left', dummy.width() + 3 + 'px');
dummy.remove();
}
} else {
input.prev('span').css('visibility', 'hidden');
}
}, 0);
};
function resetField() {
var def = $(this).attr('title');
if (!$(this).val() || ($(this).val() == def)) {
$(this).val(def);
$(this).prev('span').css('visibility', '');
}
};
var fields = $('input, textarea');
fields.live('mouseup', toggleLabel); // needed for IE reset icon [X]
fields.live('keydown', toggleLabel);
fields.live('paste', toggleLabel);
fields.live('focusin', function() {
$(this).prev('span').css('color', '#ccc');
});
fields.live('focusout', function() {
$(this).prev('span').css('color', '#999');
});
$(function() {
$('input[placeholder], textarea[placeholder]').each(
function() { toggleLabel.call(this); }
);
});
})(jQuery);
CSS
.placeholder {
background: white;
float: left;
clear: both;
}
.placeholder span {
position: absolute;
padding: 5px;
margin-left: 3px;
color: #999;
}
.placeholder input, .placeholder textarea {
position: relative;
margin: 0;
border-width: 1px;
padding: 6px;
background: transparent;
font: inherit;
}
/* Hack to remove Safari's extra padding. Remove if you don't care about pixel-perfection. */
#media screen and (-webkit-min-device-pixel-ratio:0) {
.placeholder input, .placeholder textarea { padding: 4px; }
}
Robert Nyman discusses the problem and documents his approach in his blog.
This fiddle that has all the neccessary HTML, CSS and JS.
Unfortunately, he solves the problem by changing value.
This will not work by definition if placeholder text is itself a valid input.
I found this question by googling out the solution to the same problem. It seems that existing plugins either don't work in elder browsers or hide placeholder on focus.
So I decided to roll on my own solution while trying to combine best parts from existing plugins.
You may check it out here and open an issue if you face any problems.
How about something simple like this? On focus save out the placeholder attribute value and remove the attribute entirely; on blur, put the attribute back:
$('input[type="text"]').focus( function(){
$(this).attr("data-placeholder",$(this).attr('placeholder')).removeAttr("placeholder");
});
$('input[type="text"]').blur( function(){
$(this).attr("placeholder",$(this).attr('data-placeholder'));
});
I wrote my own css3 only solution. See if that fullfills all your needs.
http://codepen.io/fabiandarga/pen/MayNWm
This is my solution:
the input element is set to "required"
an aditional span element for the placeholder is needed. This element is moved on top of the input element (position: absolute;)
with css selectors the input element is tested for validity (required fields are invalid as long as there is no input) and the placeholder is then hidden.
Pitfall: The placeholder is blocking mouseevents to the input! This problem is circumvented by hiding the placeholder element when the mouse is inside the parent (wrapper).
<div class="wrapper">
<input txpe="text" autofocus="autofocus" required/>
<span class="placeholder">Hier text</span>
</div>
.placeholder {
display: none;
position: absolute;
left: 0px;
right: 0;
top: 0px;
color: #A1A1A1;
}
input:invalid + .placeholder {
display: block; /* show the placeholder as long as the "required" field is empty */
}
.wrapper:hover .placeholder {
display: none; /* required to guarantee the input is clickable */
}
.wrapper{
position: relative;
display: inline-block;
}
Maybe you can try with Float Label Pattern :)
See Float labels in CSS