Home > Net >  centering items even with or without labels
centering items even with or without labels

Time:07-21

I have this on my codepen in which I was using flex to align items. What I want is to align items even with or without labels.

here is my html code:

<div >
<div >
<!--<label>checkbox</label> -->
<input type="text"/>
</div>
<div >
 <label>checkbox</label>
 <input type="checkbox"/>
</div>
<div >
 <label>checkbox</label>
 <input type="radio"/>
</div>
</div>

my css:

.parent-main {
display: flex;
justify-items: center;
border: solid 1px #ccc;
width: 55vh;
height: 25vh;
margin: 5px;
padding: 15px;
gap: 2px;
}

.child1 {
display: flex;
flex-direction: column;
/*   position: relative;
top: 2px; */
}

.child2 {
display: flex;
flex-direction: column;
align-items: baseline;
}

.child3 {
display: flex;
flex-direction: column;
align-items: baseline;
}

Here is my codepen link: enter link description here

This is quite tricky on my side but I hope I can have your insights on this, been working this for 2 days now.

CodePudding user response:

As you want to align the input of type "text" with the other div siblings but without it having any label element, we use a line break in order to mimic an empty blank space without any text element in it by using either <br> or &nbsp;

Tip: Avoid duplication of codes in CSS properties, see the below snippet

.parent-main {
  display: flex;
  justify-items: center;
  border: solid 1px #ccc;
  width: 55vh;
  height: 25vh;
  margin: 5px;
  padding: 15px;
  gap: 2px;
}

.parent-main>div {
  display: flex;
  flex-direction: column;
}

.child2,
.child3 {
  align-items: baseline;
}
<div >
  <div >
    <!--empty space -->
    <br>
    <!-- &nbsp; can also be used -->
    <input type="text" />
  </div>
  <div >
    <label>checkbox</label>
    <input type="checkbox" />
  </div>
  <div >
    <label>checkbox</label>
    <input type="radio" />
  </div>
</div>

  • Related