"保证金:0自动"定义宽度时不起作用

时间:2017-01-29 20:40:38

标签: html css

我正在为我的网站创建一个搜索工具,我希望它位于中心,所以我创建了主div容器,它将容纳每个搜索工具元素,其中包含margin: 0 auto并且它有效。 但在其中,另一个margin: 0 auto;的元素不会居中。

HTML:

<div class="searchbox">
        <div class="mover">
           <input type="text" name="searchfield" class="search" placeholder="Search Item">

CSS:

.searchbox {
  position: absolute;
  width: 100%;
  overflow: hidden;
  left: 0%;
  top: 55px;
  height: 350px;
  background-color: black;
}
.mover {
  display: block;
  z-index: 2;
  background-color: white;
  margin: 0 auto;
  width: 70%;
  height: 100%;
  min-width: 600px;
  height: 250px;
}
.search {
  position: relative;
  width: 70%;
  height: 35px;
  top: 100px;
  margin: 0 auto;
  border: solid 1px black;
  border-radius: 7px;
}
.search[type=text] {
  color: black;
  text-align: center;
  font-family: 'Lato';
  font-size: 15px;
}

请注意,我不希望width: 100%用于搜索元素,正如您在代码中看到的那样,我定义了min-width: 600px,这是针对移动设备中与此无关的其他元素情况下。

请查看Fiddle

问题是什么?我已经在两个元素上定义了宽度,但是自动页边距仍然不起作用,有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:3)

<input>是内联级元素,margin: auto技巧仅适用于块级元素。

你可以这样做:

.search {
  ...
  width: 70%;
  margin: 0 auto;
  display: block; /*add this line*/
}

或者,如果您愿意将其保留为内联,则可以执行以下操作:

.mover {
  text-align: center;
}
相关问题