Search code examples
htmlcsswebcss-positionfieldset

how to positioning <fieldset> tag?


I want to put the fieldset on Center.

Html code:

<html>
<head>
  <style>
    body {
      background-color: #f42b68;
      width: 100%;
    }
    fieldset {
      height: 50%;
      width: 80%;
      background: #ffffff;
    }
  </style>
</head>
<body>
  <center>
    <fieldset>
      <form>
        <input type="text" placeholder="txt">
      </form>
    </fieldset>
  </center>
</body>
</html>

Is there any possible way to do it other than using center tag?


Solution

  • You need to target the input itself rather than the fieldset, as the input has text-align: start by default. What you're looking for is:

    fieldset input {
      text-align: center;
    }
    

    To align the fieldet itself, it behaves a little differently, as it is a block element, rather than text. To align a block element centrally, you need to give it margin: auto. This can also be used with images (or any other element) by explicitly defining them as a block element with display: block:

    fieldset {
      margin: auto;
    }
    

    Keep in mind that margin: auto is stating that all four margins should have automatic offsets (centralised). That includes the top and bottom margins. You can align just the left and right margins with shorthand margin: 0 auto.

    Updated code:

    body {
      background-color: #f42b68;
      width: 100%;
    }
    fieldset {
      height: 50%;
      width: 80%;
      background: #ffffff;
      margin: auto;
      text-align: center;
    }
    fieldset input {
      text-align: center;
    }
    <body>
      <fieldset>
        <form>
          <input type="text" placeholder="txt">
        </form>
      </fieldset>
    </body>

    Hope this helps!