Chris Halcrow
Chris Halcrow

Reputation: 32010

CSS for label under input

I need a clean way of placing the label below the text input field in the following fiddle. The label needs to be center aligned to the input

.scale-options {
  margin-top: 56px;
  margin-left: auto;
  margin-right: auto;
  display: flex;
  justify-content: space-between;
  width: 1100px;
}

.scale-yes,
.scale-no,
.scale-weight {
  display: inline-flex;
  justify-content: center;
}

.scale-yes,
.scale-no {
  width: 313px;
}

.scale-weight input {
  width: 233px;
  display: block;
}

.scale-weight label {
  text-transform: uppercase;
  display: block;
  position: relative;
}
<div class="scale-options">
  <div class="scale-yes">
    <Button>yes</Button>
  </div>
  <div class="scale-weight">
    <input type="text" name="scaleWeight" value="24.5kg" disabled>
    <label for="scaleWeight" class="scale-weight-label">12.5</label>
  </div>
  <div class="scale-no">
    <Button>no</Button>
  </div>
</div>

https://jsfiddle.net/chalcrow/wzpduq2h/3/

I've tried a number of ways of doing it, like setting display:block for both the input and label, and using clear: both on both elements. I've also tried a positioning hack by setting the relative position of the label, but it breaks parts of the other layout for some reason. I've also tried setting heights and widths for the input and label and tried the suggestion here https://stackoverflow.com/a/3463670/1549918 (there are other suggested answers on that question - I looked at them all and they're either too hacky or aren't working when I try them)

Upvotes: 1

Views: 287

Answers (1)

tacoshy
tacoshy

Reputation: 13008

The issue is, that you declared display: inline-flex for .scale-weight and as such use flexbox with the default flex-direction: row Just remove the class selector from the list where you declare flexbox on it. After that you can align the text of the label with text-align: center;

.scale-options {
  margin-top: 56px;
  margin-left: auto;
  margin-right: auto;
  display: flex;
  justify-content: space-between;
}

.scale-yes,
.scale-no /* , *//* removed */
/* .scale-weight *//* removed */ {
  display: inline-flex;
  justify-content: center;
}

.scale-yes,
.scale-no 
 {
  width: 313px;
}

.scale-weight input {
  width: 233px;
  display: block;
}

.scale-weight label {
  text-transform: uppercase;
  display: block;
  /* position: relative; *//* removed as it doesn't do anything and has no absolute child */
  text-align: center; /* added */
}
<div class="scale-options">
  <div class="scale-yes">
    <Button>yes</Button>
  </div>
  <div class="scale-weight">
    <input type="text" name="scaleWeight" value="24.5kg" disabled>
    <label for="scaleWeight" class="scale-weight-label">12.5</label>
  </div>
  <div class="scale-no">
    <Button>no</Button>
  </div>
</div>

Upvotes: 2

Related Questions