P
P
Panda212018-03-19 16:16:19
css
Panda21, 2018-03-19 16:16:19

Why doesn't justify-content work when you set a width for a flex container?

Good afternoon.
I need to center align the inputs - an input field and a button (flex items) inside a form (flex container).
If I don't set the width of the flex container, then jutify-content works, but if I do, it doesn't. Googled about the width of the flex container, but did not find anything I needed. Just now "a flex container shrinks to the width of the content by default, so the width must be set explicitly", but I still don't get it. As the width of the flex container (570px), I set the sum of the widths of the flex items (390px + 180px).
I need the width and background color for the form so that between the input field and the button there is a background like the input field. Maybe it can be done differently?
The main question is how to center the form elements? What am I doing wrong?
To simplify the perception of the code, only the necessary code is left to resolve the issue, so there are no necessary attributes, etc., so as not to distract. in the sandbox

<form class="subscribe-form">
  <input class="subscribe-field">
  <input class="button-subscribe">
</form>

.subscribe-form {
  display: flex;
  justify-content: center;
  width: 570px;
  background-color: #f8f8f8;
  border-radius: 25px; 
}

.subscribe-field {
  border: none;
  background-color: #f8f8f8;
  height: 45px; 
  width: 390px;
  border-radius: 25px; 
}

.button-subscribe {
  border: none;
  height: 45px; 
  width: 180px;
  background: tomato; 
  border-radius: 25px;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-03-19
@Panda21

As the width of the flex container (570px), I set the sum of the widths of the flex items (390px + 180px).

If the sum of the widths of the elements is equal to the width of the container - what kind of alignment can we talk about? There is alignment, there is not - outwardly there will be no difference.
I guess what you want to do is actually align the container to the center of the page - add an element , for example. margin: 0 auto.subscribe-form

K
Konstantin Borovik, 2018-03-19
@PushMeNow

If I do not set the width of the flex container, then jutify-content works

You answered your own question. If you need to align inner elements then just remove the width - they are not inline objects. If you want to align the entire form, then wrap it in a div and apply the flex properties:
<div style="display:flex;justify-content:center">
  <form>
  <input class="subscribe-field">
  <input class="button-subscribe">
</form>
</div>

In general, take a closer look at the properties of flex objects. How child objects will align if you limit the free space to their total width.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question