简体   繁体   English

如何使两个元素在不同宽度的容器中并排对齐?

[英]How do I make two elements align side-by-side in a different width container?

For example: 例如:

<!-- make sure the link block fulfill the whole container -->
a {display:block;float:left;border:1px solid #ccc; width:48%}

<!-- work great in width:400px; -->
<div id=container1 style="width:400px">
  <a href="" >first element</a>
  <a href="" >second element</a>
</div>

<!-- not good! no enough space for second link block in my situation test in firefox-->
<div id=container1 style="width:200px">
  <a href="" >first element</a>
  <a href="" >second element</a>
</div>

So, is there a way to make them all fulfill and align side by side in different width of containers!? 因此,有没有办法使它们全部满足并在不同宽度的容器中并排对齐

Thank you very much!! 非常感谢你!!

It looks like you're making a list of links - if this is the case, you should use (instead of <div> ) the <ul> tag with <li> and <a> inside. 看起来您正在创建链接列表-如果是这种情况,则应在内部使用<li><a> (而不是<div> )使用<ul>标记。

If you do this you can apply the width / float rules to the <li> instead, and apply the border and display: block to the <a> tag. 如果执行此操作,则可以将width / float规则应用于<li> ,然后将borderdisplay: block应用于<a>标记。

I changed your width to 50% , as that's obviously what you're trying to achieve. 我将width更改为50% ,因为这显然是您要实现的目标。

Live Demo 现场演示


Here are two alternate solutions which will work only in modern browsers/IE8+: 这是两个仅在现代浏览器/ IE8 +中有效的替代解决方案:

  1. You can use the outline property instead of border . 您可以使用outline属性而不是border
    See: https://developer.mozilla.org/en/CSS/outline 参见: https : //developer.mozilla.org/en/CSS/outline
    Live Demo 现场演示

  2. You can use box-sizing: border-box . 您可以使用box-sizing: border-box
    See: https://developer.mozilla.org/en/CSS/box-sizing 参见: https : //developer.mozilla.org/en/CSS/box-sizing
    Live Demo 现场演示

Set margin:0; 设置边距:0; padding:0; 填充:0; for both container1 and a tags. 对于container1和标记。 That could be the problem.in 那可能就是问题所在。

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

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