How to horizontally center a DIV

后端 未结 3 1458
余生分开走
余生分开走 2021-01-25 06:09

How can I horizontally center the DIV with the textbox and button on this URL: http://tinyurl.com/d4lpyh5?

Regards, Kevin

相关标签:
3条回答
  • 2021-01-25 06:23

    Try this.

    <center>
    <input type="text" />
    </center>
    
    0 讨论(0)
  • 2021-01-25 06:29

    On line 10, you should add a width to the div: Change

    <div style="margin-left: auto; margin-right: auto;">
    

    to

    <div style="margin-left: auto; margin-right: auto;width: 700px;">
    

    Edit: If you do it this way, you'll have to change the width of the input elements to a fixed pixel value instead of width: 30%;

    0 讨论(0)
  • 2021-01-25 06:37

    margin-left: auto; and margin-right: auto divide the remaining width in half between them with the result that the element is centered. That gets you much closer, but it isn't the everything. (And unfortunately it doesn't change appearance even a little bit although it's right.)

    The reason the element doesn't look centered yet is the element is by default the full width of the container/screen. So to make horizontal centering work, you need to not only specify left and right auto margins, but go further and explicitly set the width of the element.

    One would like to be able to specify something like "width: minimum-needed;" so it would adjust automatically to whatever it contained ...but there's no such thing in CSS. The only way I know is to explicitly specify the width of the element in a way that makes sense for what you know are its contents.

    So here below for example is your code modified so it looks like my understanding of what you desire (there's probably an extra <div> in here, and you probably want to encapsulate this information in your stylesheet ...but you get the idea):

    <html>
    <head>
    <title>Page</title>
    <link rel="stylesheet" href="http://145.120.12.115/project/css/main.css"></link>
    <meta name="viewport" content="width=device-width" />
    </head>
    <body>
    <div class="top"></div>
    <div class="search">
        <div style="margin-left: auto; margin-right: auto; width: 40ex;">
          <input type="text" id="q" name="q" value="" style="width: 30ex;"/>
          <input type="submit" class="blueButton button" value="Search" />
        </div>
    </div>
    </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题