Search code examples
htmlcsscentervertical-alignment

How can I get my <p> elements to be vertically centered along side <input> and <textarea> fields?


I can't get the p, input and textarea elements all be centered with in a li elements in a user settings area I am working on right now. Right now only the input and textarea elements are being properly centered with in the li elements while the p elements are positioned right at the top. I have tried to apply

vertical-align: middle

to the li element but it failed.

My example code link is here at JS Bin

To help guide you while looking at my example, each element's background color is as follows:

  • p = red
  • li = cyan
  • input & textarea = white

How can I get the p, input and textarea elements all be centered with in a li elements?


Solution

  • I learned that sites like Twitter and Facebook create their settings pages with the following HTML elements:

    • table
    • tbody
    • tr
    • th
    • td
    • label

    So I decided to follow this standard practice and this is what I came up with. The CSS styling is not there but you can see that basic solid structure that the table element and its child elements provide. Notice how the table tbody tr th label names automatically are positioned at the center of their containing table cell. And if I need them to be positioned to the top, bottom or baseline than all I need to do is add vertical-align to label's parent element which is th.

    This is the result of adding vertical-align: top; styling to the th element in the same row as the textarea.

    And if I want to position the label elements horizontally with in the table cell then all I need to do is use the text-alignselector on the th element and presto.

    This is the result of adding text-align: right; to the 2nd th in the 2nd tr and the 3rd and 4th tr th elements.