html - 在 div 宽度 :100% leaving some margin in all sides 内居中文本框

标签 html css textbox width centering

我需要在一个 div 中放置一个文本框,该文本框的宽度为 100%,所有边都留有 margin
我的问题是我无法放置右边距,导致文本框的宽度为 100%(这是必需的!)。
所以 textbox 和 div 容器必须有 100% 的宽度(导致响应)并且 textbox 需要在所有边上留出 8px 的边距。

.search-cont {
    background-color: #c8c7cc;
    width:100%;
    height:44px;
    overflow:hidden;
    transition: all 0.5s;
    z-index:997;
    position:fixed;
}

.search-text {
    border-radius:5px;
    border:0px;
    height:28px;
    padding:0px;
    padding-left:6px;
    width: 100% !important;
    margin: 8px !important;
    box-sizing:border-box;
    display:block;
    background-color:#fff;
}

::-webkit-input-placeholder {
   text-align: center;
}

:-moz-placeholder { /* Firefox 18- */
   text-align: center;  
}

::-moz-placeholder {  /* Firefox 19+ */
   text-align: center;  
}

:-ms-input-placeholder {  
   text-align: center; 
}
<div id="search-cont" class="search-cont">
  <div><input type="text" id="search-text" class="search-text" placeholder="Search" /></div>
</div>

有例子--> DEMO

最佳答案

您可以使用 padding在父标签上而不是 margin在元素上。

您需要添加 box-sizing:border-box;到父级(最佳做法是使用 * 选择器将其添加到任何元素)。

* {
  box-sizing:border-box;  
}

body {
  margin:0;  
}

.search-cont {
  background-color: #c8c7cc;
  width:100%;
  height:44px;
  overflow:hidden;
  transition: all 0.5s;
  z-index:997;
  position:fixed;
  padding:8px;
}

.search-text {
    border-radius:5px;
    border:0px;
    height:28px;
    padding:0px;
    padding-left:6px;
    width: 100% !important;
    /*margin: 8px !important;*/
    box-sizing:border-box;
    display:block;
    background-color:#fff;
}

::-webkit-input-placeholder {
   text-align: center;
}

:-moz-placeholder { /* Firefox 18- */
   text-align: center;  
}

::-moz-placeholder {  /* Firefox 19+ */
   text-align: center;  
}

:-ms-input-placeholder {  
   text-align: center; 
}
<div id="search-cont" class="search-cont">
  <div><input type="text" id="search-text" class="search-text" placeholder="Search" /></div>
</div>

关于html - 在 div 宽度 :100% leaving some margin in all sides 内居中文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34284994/

相关文章:

html - 如何使用 Css 格式化文本框

html - 不使用线性渐变的 IMG 上的黑色渐变层?

python - 使用 IPython.display.image : sometimes work, 有时不显示来自网络的图像

css - WPBakery Accordion 背景色

jquery - 一起实现可排序和可调整大小的 Jquery UI

javascript - 想要消失输入文本框默认值

导出到 iPad 时 Css 样式发生变化

javascript - 当页面的一部分被溢出 CSS 隐藏时,如何将图像置于浏览器中心?

javascript - 使用随机的十六进制颜色,与真实生成器的值不同

C# WPF/XAML 从任何地方/任何线程访问 TextBox 帮助