user3494047 user3494047 - 5 months ago 8
CSS Question

How can I have two objects aligned horizontally (one to the right of the other) and center the left one?

I have a form which looks like this:

<div class="container">
<form action="/my-handling-form-page" method="post">
<div class="form-group">
<input type="text" name="query"/>
<button type="submit">Search</button>
</div>
</form>
</div>


and I want the input to be horizontally centered in the page and then I would like the button to be aligned with it horizontally and placed to the right of the input element. How do I do this?

I have tried making them both display: inline-block and centering the input but I can't get it to work.

Also I am using bootstrap if that helps/doesn't.
Here is a fiddle of the whole thing

Answer

You could use the table layout on .form-group to shrink it on its content and center it via margin:

body {
    margin: 10px;
}
.form-group{
  display:table;
 margin: 0 auto;
}

input, button{
float: left;
}
/* optionnal to take button off from center calculation */

/* demo purpose */
html:hover button {
  position:absolute;
  }

body {
  min-height:100%;
  background:linear-gradient(to left, transparent 50%, lightgray 50%);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
    <form action="/my-handling-form-page" method="post">
      <div class="form-group">
        <input type="text" name="query" class="searchbar same-line centered"/>
        <button type="submit" class="same-line">Search</button>
      </div>
    </form>
</div>

to keep button off center, you may use padding and absolute :

body {
    margin: 10px;
}
.form-group{
  display:table;
 margin: 0 auto;
  padding:0 5em;/* to keep button in sight if window comes very small */
}

input, button{
float: left;
}

button {
  position:absolute;
  }

body {
  min-height:100%;
  background:linear-gradient(to left, transparent 50%, lightgray 50%);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
    <form action="/my-handling-form-page" method="post">
      <div class="form-group">
        <input type="text" name="query" class="searchbar same-line centered"/>
        <button type="submit" class="same-line">Search</button>
      </div>
    </form>
</div>

Comments