html - 使用CSS动态更改宽度以调整另一个div内的div

标签 html css

我正在尝试创建一个带有输入文本和其中两个按钮的自定义 div,如下所示。 enter image description here

但是当我调整屏幕大小时它变成了这样 enter image description here

有没有办法避免两个按钮掉下来?相反,它应该保留在原始 div 中。

这是我试过的代码:

.searchBar {
	background: #DDDDDD;
	width:100%;
	height:50px;
	padding: 10px;
	position: relative;
}

.search_field {
	display: inline-block;
	border-radius:4px ;
	background: #FFFFFF;
	width: 70%;height: 32px;
	position: relative;
	left: 60px;
	overflow: inherit;
}

.search_field input {
	width: 89%;
	padding: 0;
	border-top-left-radius: 4px;
	padding-left: 10px;
	padding-top: 5px;
	padding-bottom: 5px;
	border:1px inset red;
}

.search_field input:focus {
	outline-color: transparent;
	outline-style: none;
}

.search_field button {
	border: none;
	background: none;
}
<div id="searchBar" class="searchBar">
	<div class="search_field">                
		<input type="text" id="searchInput" placeholder="Search" oninput="showSearchButtons()"/>
		<button id="btn1"  hidden="true" onclick="alert()"><img src="assets/images/search.png"></button>                    
		<button id="btn2" hidden="true" onclick="alert()"><img src="assets/images/saveBtn.png"></button>
	</div>
</div>

感谢任何帮助。谢谢

最佳答案

您可以使用 calc 来计算输入元素相对于按钮的宽度:

width: calc(100% - 100px);

只需确保按钮的宽度取100%。在 SASS 中它可能看起来像这样:

$buttons: 50px;
width: calc(100% - #{$buttons * 2});

下面是一个简化的实现。我仍然将 % 值作为旧版浏览器的后备方案 - 但这是一种习惯,而不是必要的,因为每个主要浏览器都支持 calc,甚至是 IE9 及更高版本。

input, button {
    float: left;
    height: 50px;
    display: block;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    border: none;
}
input {
    width: 70%;
    width: calc(100% - 100px);
    padding: 10px;
}
button {
    /* Note that this width is equal to 100% 
    /* minus the percentage width of the input 
    /* divided by the amount of buttons. */
    width: 15%; 
    width: 50px;
    line-height: 50px;
}
/* This rule is just to make sure your images don't decide the buttons width */
button img {
    max-width: 100%;
    display: inline-block;
}
<input type='text' placeholder='search' />
<button><img src="http://placehold.it/50x50" /></button>
<button><img src="http://placehold.it/50x50" /></button>

关于html - 使用CSS动态更改宽度以调整另一个div内的div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33388435/

相关文章:

Javascript 生成文件并要求用户保存它,可能吗?

html - CSS:使用 50% 时 Div 框不均匀

javascript - 有没有办法通过添加 javascript 文本节点让滚动条自动向下移动到 div 的最新添加内容?

javascript - 我的旋转木马在循环到第 3 张幻灯片时会放大和缩小?

html - 如何将非透明文本放入 opac div 框中

javascript - Safari 中未触发变声事件

html - 在页面加载时隐藏滑动/推送菜单?

javascript - 将单选按钮值传递给 mysql 查询

html - 图像适合 div 大小并可点击

html - Bootstrap 网格拉/推行