简体   繁体   English

HTML / CSS-如何根据其内容调整div的大小?

[英]HTML/CSS - How do I make divs to size according to their contents?

I have 2 divs side by side. 我有2个div并排。

In the first div, I have 2 labels side by side, and one input text below them. 在第一个div中,我并排有2个标签,并且在它们下方有一个输入文本。 One of the labels is an error information. 标签之一是错误信息。 Sometimes it will be displayed, sometimes not. 有时会显示,有时则不会。 When it's not display, I'd like the div to resize to be smaller, so the second div can be closer to it. 当它不显示时,我希望将div的大小调整为较小,以便第二个div可以更接近它。

The second thing is the same thing, except it has one label div, therefore it doesn't requires a resize. 第二件事是同一件事,除了它有一个标签div,因此不需要调整大小。

Is there a way to achieve what I want? 有没有办法实现我想要的? There is an awesomely drawn example of what I want to acahieve below: 下面是我想知道的一个很棒的示例:

自动调整宽度的惊人示例

This is the code. 这是代码。

<div id="main-div">
<div id="address-number-div">
    <label>Number</label>
    <label class="error" id="number-error">Empty Field</label>
    <input id="number-input" onfocus="onfocus('number-error')"/>
</div> 

<div id="address-complement-div">
    <label>Complement</label>
    <input id="complement-input" />
</div>

and CSS: 和CSS:

div {border: 1px solid #000000; padding: 5px;}

.error{color:#FF0000; margin-left:5px;}

#main-div div {display:inline-block;}

#main-div input {display:block;}

#number-input {
    width: 16%;
}​

Set them to display: inline-block; 将它们设置为display: inline-block; to let them shrink to fit the the content. 让它们缩小以适合内容。

Have a look at this DEMO . 看看这个演示

Floating your divs left should solve this problem. 向左浮动div应该可以解决此问题。

Don't give width <persentage> type value, give <length> : 不要给出width <persentage>类型的值,而给出<length>

#number-input { width: 24px; }​

See it with your code on my fiddle . 我的小提琴上看到您的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 DIVS 使用 Html 和 CSS 制作网格 - How do I make a grid with Html and CSS with DIVS 如何在CSS中制作此布局,divs正在崩溃 - How do i make this layout in css, divs are collapsing CSS和HTML - 如何使div不重叠? - CSS and HTML - How to make divs not overlap? 如何根据 Angular/Ionic 中的屏幕尺寸使 CSS/HTML 边距响应 - How do I make CSS/HTML margins responsive based on screen size in Angular/Ionic 如何使用 HTML 和 CSS 在页面上制作相同大小的图像? - How do I make images the same size on a page using HTML and CSS? CSS-如何使两个右div的高度等于左div的高度 - css - How do I make the height of two right divs equal the height of the left divs 当我将浏览器宽度更改为平板电脑或移动设备尺寸的小尺寸或xs时,HTML / CSS不合适 - HTML/CSS when I change browser width to small or xs for tablets and mobile size, contents do not fit 如何根据 flexbox 中的 window 大小使项目的大小发生变化? - How do I make the items change in size according to the window size inside a flexbox? 如何根据屏幕大小缩放HTML中元素的大小? - How do I scale the size of the elements in my HTML according to screen size? 在 HTML/CSS 中,如何使表情符号与文本大小相同? - In HTML/CSS how can I make emoji the same size as the text?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM