-2

A task I'm attempting; model a certain html page to look like the Google home page. I am struggling to centre the search bar and the buttons using CSS.

div.search {
  display: block;
  margin-left: auto;
  margin-right: auto;
}
<div class="search">
  <form action="https://google.com/search">
    <br><input type="text" name="q"></br>
    <input type="submit" value="Google Search">
    <input type="submit" value="I'm Feeling Lucky">
  </form>
</div>

But the positions of the search box and two buttons don't change.

j08691
  • 204,283
  • 31
  • 260
  • 272
Paulisto
  • 25
  • 4
  • block-level elements will span the entire width by default and as such can't be centered horizontally – tacoshy May 17 '22 at 21:31
  • You'd have to also give the div a width less than 100% for that to work – j08691 May 17 '22 at 21:33
  • remove `margin` from the div as it is an useless property this way. Use `text-align: center` on the div to center the buttons: `div.search { text-align: center; }` – tacoshy May 17 '22 at 21:36
  • thanks @tacoshy, I've been struggling for hours and I didn't realise it was that simple – Paulisto May 17 '22 at 21:45

1 Answers1

-1

You're trying to center inner elements with margin but applying the props to their parent element.

If you want to have inner elements centered using margin, you need to apply it to them, NOT on their parent.

Try this:

  1. Apply the margin: 0 auto; to all your inputs (to center all of them).
  2. Set the search bar display to display: block (so your search bar ocuppies the entire line)
  3. Set the submit buttons display to display: inline: block; (so they're are displayed inline)
  4. Remove both <br> around your search input (as they're doing nothing).

Code:

div.search{
  width: fit-content;
}

input[type="text"]{
  display: block;
}

input[type="submit"]{
  display: inline-block;
}

input{
  margin: 0 auto;
}
<div class="search">
  <form action="https://google.com/search">
    <input type="text" name="q">
    <input type="submit" value="Google Search">
    <input type="submit" value="I'm Feeling Lucky">
  </form>
</div>
Petri
  • 1
  • 1
  • you need 16 lines of CSS code that could have done with just 1. – tacoshy May 17 '22 at 22:38
  • Yes, but at some point he's going to style all these inputs, or even add more of them. – Petri May 18 '22 at 14:44
  • Even then it would be easier to use flexbox or text-align and align all the child elements with one property then selecting every single element... – tacoshy May 18 '22 at 15:58