-3

How can I apply horizontal align to <label> element? If I do this <label><p>3</p></label> everything works fine. I don’t understand why <p> element has auto margin (centred) when <label> is not.

html

body {
  background: #2b2b2b;
  font-size: 36px;
  font-family: Helvetica neue, roboto;
  color: white;
}
.main {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  width: 75%;
  margin: 0 auto;
  background: black;
}
.common {
  width: 45%
}
#div1 {
  background: purple;
  text-align: right;
}
#div2 {
  background: orange;
}
#div3 {
  background: olive;
  text-align: right;
}
#div4 {
  background: gray;
}
label {
  
}
<div class="main">
  <div id="div1" class="common">1</div>
  <div id="div2" class="common">2</div>
  <div id="div3" class="common"><label for="name-label">3</label></div>
  <div id="div4" class="common"><p>4</p></div>
</div>
raziEiL
  • 77
  • 2
  • 6

1 Answers1

2

By default p elements are display: block and label elements are display: inline.

margin: auto will centre a block element. It won't centre an inline element.

Use text-align: center (and not right) on the parent of an inline element (the <div> in this case) to centre the content within it.


The p element in your example, is not centred, it is left aligned. If it had margin: auto then it would be centred.


If you were talking about vertical alignment (which isn't what you said) then the p element is in the vertical centre, but that is because it has equal top and bottom margins from the user-agent stylesheet and its content height combined with the margins make it the tallest thing there. If the content in block 3 was taller, then the paragraph would be closer to the top than the bottom of its containing div.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • maybe you can try `flex-flow : row` because it can be align on the row – LucasLaurens Apr 04 '19 at 09:19
  • @Quentin Uhm... why label element won't centre anyway? `label { display: block; margin: auto; }` – raziEiL Apr 04 '19 at 09:31
  • A block is also, by default, as wide as the space that contains it, so alignment in any direction has no visible effect unless you also change the `width`. – Quentin Apr 04 '19 at 09:32