behzad razzaqi behzad razzaqi - 5 months ago 37
CSS Question

How can set text box to center of td tag in html table?

I spilit the screen with html table,left panel show image and right panel want to show text box,but text box not show the center of td tag,this html code:


<table style="width:100vw">
<tr>
<td style="width:50vw;height:100vh;" align="left">
<img src="../Content/45.png" style="display:block;max-width:50vw;max-height:100vh" />
</td>
<td style="width:50vh;text-align:center;">
<div style="top:50%;">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</td>
</tr>
</table>




and this is my output:

enter image description here


but i want this output:

enter image description here


How can i solve that?

Answer

The div you use is a block element and as such, will use full width of its parent.

Updated base on comment:

For vertical alignment, use vertical-align: middle, updated the CSS rule to this

td { padding: 0; vertical-align: middle; }

For horizontal alignment:

In your case you need to set text-align: center on the div instead of the td, like this <div style="top:50%;text-align:center;">

html, body {
  margin: 0;
}
table {
  border-collapse: collapse;
}
td {
  padding: 0;
  vertical-align: middle;
}
<table style="width:100vw">
  <tr>
    <td style="width:50vw;height:100vh;" align="center">
      <img src="http://lorempixel.com/600/600/animals" style="display:block;max-width:50vw;max-height:100vh" />
    </td>
    <td style="width:50vh;">
      <div style="top:50%;text-align:center;">
        <input ID="TextBox1" type="text">
      </div>
    </td>
  </tr>
</table>

Or make the div display: inline-block, <div style="top:50%;display: inline-block">

html, body {
  margin: 0;
}
table {
  border-collapse: collapse;
}
td {
  padding: 0;
  vertical-align: middle;
}
<table style="width:100vw">
  <tr>
    <td style="width:50vw;height:100vh;" align="center">
      <img src="http://lorempixel.com/600/600/animals" style="display:block;max-width:50vw;max-height:100vh" />
    </td>
    <td style="width:50vh;text-align:center;">
      <div style="top:50%;display: inline-block">
        <input ID="TextBox1" type="text">
      </div>
    </td>
  </tr>
</table>