简体   繁体   English

如何仅使用CSS使div组具有相同的宽度?

[英]How to make groups of divs the same width using only CSS?

I've got a group of buttons (divs) which I would like to be the same length for all buttons within a logical group. 我有一组按钮(div),我希望逻辑组中所有按钮的长度相同。

I could simply do a min-length for the CSS style of the button, however some button groups are short, while others are very long. 我可以简单地为按钮的CSS样式设置min-length ,但是某些按钮组很短,而另一些则很长。 This makes a uniform min-length either insufficient for long groups or wasteful/stupid looking for short ones. 这使得统一的min-length对于长组来说是不够的,或者对于短组来说是浪费/愚蠢的。 Additionally, multiple groups (short and long) can appear on the same screen. 此外,多个组(短和长)可以出现在同一屏幕上。

按钮布局示例

(These divs are all styled with display: inline-block , so that's why they don't fill the width of the container) (这些div都使用display: inline-block样式,因此这就是为什么它们不填充容器的宽度)

I've thought of a few nasty solutions to this, but none are preferable: 我想到了一些讨厌的解决方案,但没有一个是更可取的:

  • Set a specific min-length for each group 为每个组设置特定的min-length
  • Use JavaScript to resize the buttons 使用JavaScript调整按钮的大小

I was wondering if there was a generic, pure CSS solution to the above problem instead of using either of these methods. 我想知道是否有一个通用的纯CSS解决方案来解决上述问题,而不是使用这两种方法。 Thanks for any help you can provide. 感谢您的任何帮助,您可以提供。


Edit : Here is the markup and CSS I've got so far. 编辑 :这是到目前为止的标记和CSS。 Pretty simple: 很简单:

HTML: HTML:

<div class="wrapper">
    <div class="button">Lorem ipsum</div>
    <div class="button">Lorem ipsum dolar</div>
    <div class="button">Lorem</div>
</div>

CSS: CSS:

div.button { display: inline-block; min-width: 50px; }

Wrap similar buttons in a container div with a desired width and set the inners divs to: 将类似的按钮包装在具有所需宽度的容器div中,并将内部div设置为:

box-sizing: border-box;
width: 100%;

This will allow you to edit the widths of a logical grouping in one place. 这将使您可以在一处编辑逻辑分组的宽度。

wrap them both in a container. 将它们都包装在一个容器中。

<div class="group">
    <div class="button">Hi</div>
    <div class="button">Wassup</div>
    <div class="button">Yo</div>
</div>

then apply css like this: 然后像这样应用CSS:

    display:inline-block;
    min-width: 100%;

and then set the div "group" that groups those divs in the width you wanted to 然后设置div“组”,以将这些div分组为所需的宽度

Use min-width and max-width: 使用最小宽度和最大宽度:

div{/*use the selector what you're using*/
  min-width: 150px;
  max-width: 350px;
  width: auto;
  display: inline-block;
}

If you want to get a uniform width, then you have to define a class name and style like this: 如果要获得统一的宽度,则必须定义一个类名和样式,如下所示:

.width1{
  width: 200px;
}

.width2{
  width: 300px;
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM