Reputation: 5454
The HTML below defines a text input and a submit button. I'd like them to be right next to each other, with no gap. When my code looks like this there's a strange gap in there, even though I have margin set to 0 on all input elements
<form action="http://google.com/search" method="get" class="search">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
however if there's no line break in the HTML between the 2 inputs
<form action="http://google.com/search" method="get" class="search">
<input type="text" name="q"><input type="submit" value="Search">
</form>
the mystery gap goes away, and the page looks like I think it should! My HTML and CSS are both 100% valid.
Is there any way for me to fix this with CSS? I can't guarantee where the breaks will be in the HTML.
Thanks in advance!
Upvotes: 2
Views: 176
Reputation: 1146
Here you are the solution:
<form action="http://google.com/search" method="get" class="search">
<input type="text" name="q" style="margin:0"><input type="submit" value="Search" style="margin:0">
</form>
Upvotes: -1
Reputation: 651
This is a very well known issue and is technically not a "bug": the spaces in the HTML get interpreted as spaces between words and as such displayed as a whitespace character.
As suggested, floating will most likely solve the issue, though there is another hack I use at times to get rid of the inline-block
elements spaces, and that is, setting the container font-size
to 0, and, if necessary, resetting the property in the children elements.
In your case this rule should suffice to erase your problem:
form.search {
font-size: 0
}
Upvotes: 0
Reputation: 700152
The mystery is just a space character. The input elements are inline elements, and all white space characters (including the line break) are interpreted as space characters in HTML.
You can make the input elements block elements and float them next to each other. Applying an overflow
setting on the form (but no size) will make it contain the floating elements, so that they don't extend outside the form.
CSS code:
.search { overflow: hidden; }
.search input { float: left; }
Upvotes: 3
Reputation: 21708
You can leave display
set to either inline
or inline-block
and try and offset it with negative margins, e.g.,
input { margin-right: -0.4em; }
Or you can float your elements (which will automatically set them to display:block
):
input { float: left; }
/* overflow: auto on the parent of floated elements will "shrink wrap" its floated content */
form { overflow: auto; }
Upvotes: 0
Reputation: 128991
Your newline and indentation insert a space. In general, there is no way to fix it without editing the HTML, but you may be able to make the elements display: block
and float them, which will make the space go away. This won't work in all cases, though.
Upvotes: 0