What's keeping my input element from displaying like a block element? - css

http://jsfiddle.net/aam7J/
How would I induce div-like behaviour on the input element? Specifically, how can I induce the width to expand such that its outer width including margin fills up the container? width: 100% doesn't work, because it doesn't take into account the other box model attributes.

I use a "hack" to account for the input border width something like this...
<div>hello world</div>
​
<div class="adjustForTheInputBorder">
<input type="text" />
</div>
input
{
width:100%;
border-width:2px;
}
div.adjustForTheInputBorder
{
margin-right: 4px; /* or 2x whatever your input border width is */
}
div
{
background-color: pink;
}
My adjustForTheInputBorder class tends to have a name which more appropriately conveys my hatred of css though... :)
P.S. div renders as display:block by default, you don't need that there.

Related

Using "margin:0 auto;" and background-color without inner div

I want a centred block using auto left/right margins, but I also want it to have a background colour. Since background colour is not applied to the margin area of a block, I'm using a block with the background colour set, and then an inner block with the auto margins.
I don't like this, since it requires extraneous markup. Is there a technique to achieve this while just using a single block?
Update: to clarify, I want to achieve the same thing with only one block, not two; in the example below I want to drop the inner div.
Bare bones code I'm using at present:
<section id="example">
<div id="inner">
<h1>Example</h1>
<p>Example content.</p>
</div>
</section>
<style>
#example {
background-color:#ccc;
}
#inner {
margin:0 auto;
padding:10px 0;
width:500px;
background:white;
}
</style>
Couldn't find anything searching the site or Google.
Thanks in advance,
Nigel
Because you want the div#inner to be centered, it will always be in a parent. In this case another element #portfolio, but it could also be body. This solution would be perfectly acceptable.
You could try adding negative margins and some paddings, but you would complicatie things allot. What you have now makes sence to me, one element that fills the width and gives the full a background color, and one element which gets positioned in center
If you have a fixed set of block elements, you can set the margin on all the children of #example. Here is a jsFiddle.
Problem is what you save in HTML markup, you waste in CSS and it is under the assumption that you only have block children. Adding, for example, a <span> tag would break this flow, they would themselves need to be wrapped in a block container.
HTML
<section id="example">
<h1>Example</h1>
<p>Example content.</p>
</section>
CSS
#example {
background-color:#ccc;
}
#example > * {
width: 200px;
margin: 0 auto;
}

How to make a div have a fixed size?

I made a site so when you click the button 30px it changes the font inside the div.
I have a ul inside it with the bottons. When I change the size of font the div expands and the nav buttons move with it as well.
How do i make it so it stays fixed but the fonts can still change.
Try the following css:
#innerbox
{
width:250px; /* or whatever width you want. */
max-width:250px; /* or whatever width you want. */
display: inline-block;
}
This makes the div take as little space as possible, and its width is defined by the css.
// Expanded answer
To make the buttons fixed widths do the following :
#innerbox input
{
width:150px; /* or whatever width you want. */
max-width:150px; /* or whatever width you want. */
}
However, you should be aware that as the size of the text changes, so does the space needed to display it. As such, it's natural that the containers need to expand. You should perhaps review what you are trying to do; and maybe have some predefined classes that you alter on the fly using javascript to ensure the content placement is perfect.
you can give it a max-height and max-width in your .css
.fontpixel{max-width:200px; max-height:200px;}
in addition to your height and width properties
Thats the natural behavior of the buttons. You could try putting a max-width/max-height on the parent container, but I'm not sure if that would do it.
max-width:something px;
max-height:something px;
The other option would be to use the devlopr tools and see if you can remove the natural padding.
padding: 0;
<div>
<img src="whatever it is" class="image-crop">
</div>
/*mobile code*/
.image-crop{
width:100%;
max-height: auto;
}
/*desktop code*/
#media screen and (min-width: 640px) {
.image-crop{
width:100%;
max-height: 140px;
}
Use this style
<div class="form-control"
style="height:100px;
width:55%;
overflow:hidden;
cursor:pointer">
</div>
<div class="ai">a b c d e f</div> // something like ~100px
<div class="ai">a b c d e</div> // ~80
<div class="ai">a b c d</div> // ~60
<script>
function _reWidthAll_div(classname) {
var _maxwidth = 0;
$(classname).each(function(){
var _width = $(this).width();
_maxwidth = (_width >= _maxwidth) ? _width : _maxwidth; // define max width
});
$(classname).width(_maxwidth); // return all div same width
}
_reWidthAll_div('.ai');
</script>

HTML/CSS - How do I make divs to size according to their contents?

I have 2 divs side by side.
In the first div, I have 2 labels side by side, and one input text below them. One of the labels is an error information. Sometimes it will be displayed, sometimes not. When it's not display, I'd like the div to resize to be smaller, so the second div can be closer to it.
The second thing is the same thing, except it has one label div, therefore it doesn't requires a resize.
Is there a way to achieve what I want? There is an awesomely drawn example of what I want to acahieve below:
This is the code.
<div id="main-div">
<div id="address-number-div">
<label>Number</label>
<label class="error" id="number-error">Empty Field</label>
<input id="number-input" onfocus="onfocus('number-error')"/>
</div>
<div id="address-complement-div">
<label>Complement</label>
<input id="complement-input" />
</div>
​
and CSS:
div {border: 1px solid #000000; padding: 5px;}
.error{color:#FF0000; margin-left:5px;}
#main-div div {display:inline-block;}
#main-div input {display:block;}
#number-input {
width: 16%;
}​
Have a look at this DEMO.
Floating your divs left should solve this problem.
Set them to display: inline-block; to let them shrink to fit the the content.
Don't give width <persentage> type value, give <length>:
#number-input { width: 24px; }​
See it with your code on my fiddle.

width:auto for <input> fields

Newbie CSS question. I thought width:auto for a display:block element meant 'fill available space'. However for an <input> element this doesn't seem to be the case. For example:
<body>
<form style='background:red'>
<input type='text' style='background:green; display:block; width:auto'>
</form>
</body>
Two questions then:
Is there a definition of exactly what width:auto does mean? The CSS spec seems vague to me, but maybe I missed the relevant section.
Is there a way to achieve my expected behavior for a input field - ie. fill available space like other block level elements do?
Thanks!
An <input>'s width is generated from its size attribute. The default size is what's driving the auto width.
You could try width:100% as illustrated in my example below.
Doesn't fill width:
<form action='' method='post' style='width:200px;background:khaki'>
<input style='width:auto' />
</form>
Fills width:
<form action='' method='post' style='width:200px;background:khaki'>
<input style='width:100%' />
</form>
Smaller size, smaller width:
<form action='' method='post' style='width:200px;background:khaki'>
<input size='5' />
</form>
UPDATE
Here's the best I could do after a few minutes. It's 1px off in FF, Chrome, and Safari, and perfect in IE. (The problem is #^&* IE applies borders differently than everyone else so it's not consistent.)
<div style='padding:30px;width:200px;background:red'>
<form action='' method='post' style='width:200px;background:blue;padding:3px'>
<input size='' style='width:100%;margin:-3px;border:2px inset #eee' />
<br /><br />
<input size='' style='width:100%' />
</form>
</div>
"Is there a definition of exactly what width:auto does mean? The CSS
spec seems vague to me, but maybe I missed the relevant section."
No one actually answered the above part of the original poster's question.
Here's the answer:
http://www.456bereastreet.com/archive/201112/the_difference_between_widthauto_and_width100/
As long as the value of width is auto, the element can have horizontal
margin, padding and border without becoming wider than its container...
On the other hand, if you specify width:100%, the element’s total
width will be 100% of its containing block plus any horizontal margin,
padding and border... This may be what you want, but most likely it isn’t.
To visualise the difference I made an example:
http://www.456bereastreet.com/lab/width-auto/
ORIGINAL answer using Angular: Because input's width is controlled by it's size attribute, this is how I initialize an input width according to its content:
<input type="text" class="form-list-item-name" [size]="myInput.value.length" #myInput>
UPDATE for JavaScript (10/01/2022): My original answer was from the time I was studying Angular. If you need pure, Vanilla JavaScript the solution is even simpler:
<input type="text" oninput="this.size = this.value.length">
Or add an "input" event listener to your input html element and run a code like this:
const myInput = document.querySelector('input');
myInput.addEventListener('input', this.typing);
(...)
typing(e) {
e.target.setAttribute('size', e.target.value.length);
}
Obs: Depending on the browser, input may restore to its default size of something between 150px and 250px if/when size gets the 0 value. In this case, just add +1 to value.length:
<input type="text" oninput="this.size = this.value.length + 1">
OR:
typing(e) {
e.target.setAttribute('size', e.target.value.length + 1);
}
As stated in the other answer, width: auto doesn't work due to the width being generated by the input's size attribute, which cannot be set to "auto" or anything similar.
There are a few workarounds you can use to cause it to play nicely with the box model, but nothing fantastic as far as I know.
First you can set the padding in the field using percentages, making sure that the width adds up to 100%, e.g.:
input {
width: 98%;
padding: 1%;
}
Another thing you might try is using absolute positioning, with left and right set to 0. Using this markup:
<fieldset>
<input type="text" />
</fieldset>
And this CSS:
fieldset {
position: relative;
}
input {
position: absolute;
left: 0;
right: 0;
}
This absolute positioning will cause the input to fill the parent fieldset horizontally, regardless of the input's padding or margin. However a huge downside of this is that you now have to deal with the height of the fieldset, which will be 0 unless you set it. If your inputs are all the same height this will work for you, simply set the fieldset's height to whatever the input's height should be.
Other than this there are some JS solutions, but I don't like applying basic styling with JS.
It may not be exactly what you want, but my workaround is to apply the autowidth styling to a wrapper div - then set your input to 100%.
If you're willing to include a little JavaScript to solve this, you can get exact sizing. This doesn't rely on approximating width with size or ems, doesn't rely on any hardcoded element widths, and works for e.g., type="number", which don't accept a size attribute.
The trick is to get your input sized exactly like a span with the same content, by actually having an invisible span with the same content.
Put your input inside a div along with a span that mirrors the input's value. Give both the input and the span the same styling, give the input 100% width, then hide the span and absolute-position the input to sit on top of the span.
This way, the container (and thus the input) are automatically sized by the visual appearance of the content of the invisible span.
https://codepen.io/spiffytech/pen/abwWRqo
<div id="relative-parent">
<span id="size-calibration"></span>
<input id="autosized-input" />
</div>
<style>
#relative-parent {
position: relative;
/* Have some width if the input is empty */
min-width: 1em;
/* Adjust size to match the span */
width: min-content;
}
#size-calibration {
visibility: hidden;
/* Prevent the span from wrapping the text when input value has multiple words, or collapsing multiple spaces into one */
white-space: pre;
}
#autosized-input {
position: absolute;
left: 0;
width: 100%;
}
#size-calibration, #autosized-input {
/* Normalize styles that the browser sets differently between spans and inputs.
Ideally, use a "CSS reset" here. */
font-family: "Arial";
padding: 0;
/* Demonstrate that this works for input with custom styles */
font-size: 24px;
}
</style>
<script>
function updateSize() {
const span = document.getElementById('size-calibration');
const input = document.getElementById('autosized-input')
span.innerText = input.value;
}
document.addEventListener('DOMContentLoaded', () => {
const input = document.getElementById('autosized-input');
input.oninput = updateSize;
// Provide some initial content
input.value = "I'm sized exactly right!"
updateSize();
})
</script>
After tried methods all above and failed, I workaround by modifying   width property in style by unit em:
tgt.style.width = `${(tgt.value.length + 1) / 2}em`
The only option I can think of is using width:100%. If you want to have a padding on the input field too, than just place a container label around it, move the formatting to that label instead, while also specify the padding to the label. Input fields are rigid.
Answer 1 - "response" gave a nice answer/link for it. To put it in short, "auto" is the default, so it is like removing any changes in the width of an element
Answer 2 - use width: 100% instead. It will fill the 100% of the parent container, in this case, the "form".
Using JQuery
$(document).on('input', '.input-fit-width', (e) => {
$(e.currentTarget).attr('size',e.currentTarget.value.length);
})
Nowdays, flex or grid makes it much easier , it overrides default style/behaviors of https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input#size which has a default value set at 20 see : https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input#size
Giving you 2 plain CSS options without requiring JavaScript nor setting width to 100% and deal with box-sizing.
flex/flex-grow
<form style='background:red;display:flex;'>
<input type='text' style='background:green; flex-grow:1'>
</form>
grid
<form style='background:red;display:grid;'>
<input type='text' style='background:green;'>
</form>
Jquery way of adjusting size of input automatically.
In general:
$('#my_input_id').width( ($('#my_input_id').val().length) + "ch" );
On text input:
$(document).on("input", '#my_input_id', function () {
$(this).width( ($(this).val().length) + "ch" );
});
I think the simplest solution is to set parent element's width:
form{
width: 100%!important;
}

How do I set the size of an HTML text box?

How do I set the size of an HTML text box?
Just use:
textarea {
width: 200px;
}
or
input[type="text"] {
width: 200px;
}
Depending on what you mean by 'textbox'.
Your markup:
<input type="text" class="resizedTextbox" />
The CSS:
.resizedTextbox {width: 100px; height: 20px}
Keep in mind that text box size is a "victim" of the W3C box model. What I mean by victim is that the height and width of a text box is the sum of the height/width properties assigned above, in addition to the padding height/width, and the border width. For this reason, your text boxes will be slightly different sizes in different browsers depending on the default padding in different browsers. Although different browsers tend to define different padding to text boxes, most reset style sheets don't tend to include <input /> tags in their reset sheets, so this is something to keep in mind.
You can standardize this by defining your own padding. Here is your CSS with specified padding, so the text box looks the same in all browsers:
.resizedTextbox {width: 100px; height: 20px; padding: 1px}
I added 1 pixel padding because some browsers tend to make the text box look too crammed if the padding is 0px. Depending on your design, you may want to add even more padding, but it is highly recommend you define the padding yourself, otherwise you'll be leaving it up to different browsers to decide for themselves. For even more consistency across browsers, you should also define the border yourself.
input[type="text"]
{
width:200px
}
Your textbox code:
<input type="text" class="textboxclass" />
Your CSS code:
input[type="text"] {
height: 10px;
width: 80px;
}
or
.textboxclass {
height: 10px;
width: 80px;
}
So, first you select your element with attributes (look at first example) or classes(look last example). Later, you assign height and width values to your element.
This works for me in IE 10 and FF 23
<input type="text" size="100" />
If you don't want to use the class method you can use parent-child method to make changes in the text box.
For eg. I've made a form in my form div.
HTML Code:
<div class="form">
<textarea name="message" rows="10" cols="30" >Describe your project in detail.</textarea>
</div>
Now CSS code will be like:
.form textarea {
height: 220px;
width: 342px;
}
Problem solved.
Lookout! The width attribute is clipped by the max-width attribute.
So I used....
<form method="post" style="width:1200px">
<h4 style="width:1200px">URI <input type="text" name="srcURI" id="srcURI" value="#m.SrcURI" style="width:600px;max-width:600px"/></h4>
You can make the dependent input width versus container width.
.container {
width: 360px;
}
.container input {
width: 100%;
}
Try:
input[type="text"]{
padding:10px 0;}
This is way it remains independent of what textsize has been set for the textbox. You are increasing the height using padding instead
Elements can be sized with the height and width attributes.

Resources