How to horizontally center a DIV

a 夏天 提交于 2019-12-02 11:32:34

问题


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

Regards, Kevin


回答1:


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%;




回答2:


Try this.

<center>
<input type="text" />
</center>



回答3:


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>


来源:https://stackoverflow.com/questions/10690464/how-to-horizontally-center-a-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!