繁体   English   中英

动态将元素宽度的宽度更改为固定宽度

[英]Dynamically change the width of an element width a fixed width

我有一个固定宽度的div宽度:

// CSS

@media only screen
.column.small-centered:last-child, .columns.small-centered:last-child {
  float: none;
}
.lesson_lt_mc_div .small-centered {
  margin-top: 15px;
  margin-bottom: 15px;
  width: 296px;
}
foundation.css:1@media only screen
.column.small-centered, .columns.small-centered {
  margin-left: auto;
  margin-right: auto;
  float: none;
}
.text-left {
  text-align: left !important;
}

// HTML

<div class="small-3 small-centered text-left columns">
    <input type="radio" name="lt_mc_ans" value="1" id="lt_mc_ans_1"><span> 1. </span>
    <label for="lt_mc_ans_1">I</label>
    <br>
    <input type="radio" name="lt_mc_ans" value="2" id="lt_mc_ans_2"><span> 2. </span>
    <label for="lt_mc_ans_2">rsr rs rsrs rsrs r rrrs</label>
    <br>
    <input type="radio" name="lt_mc_ans" value="3" id="lt_mc_ans_3"><span> 3. </span>
    <label for="lt_mc_ans_3">Very</label>
    <br>
    <input type="radio" name="lt_mc_ans" value="4" id="lt_mc_ans_4"><span> 4. </span>
    <label for="lt_mc_ans_4">She</label>
</div>

在此处输入图片说明

我使用固定宽度的原因是我希望div居中并且文本要向左对齐。 问题是,当文本太长时会自动换行,从而使选项看起来很难看。

有没有一种方法可以使用jQuery或JavaScript动态更改div的宽度? (尽管我怀疑有任何解决方案,但我也对CSS解决方案持开放态度)。

USE display:table; margin:auto; display:table; margin:auto; 在小中心类上并删除宽度...

使用内部和外部元素。

将外部元素的文本居中对齐。 并将内部元素显示为行内块,因此它的宽度仅取决于其内容。

 .outer { text-align: center; background: lightblue; } .inner { background: lightgreen; display: inline-block; text-align: left; } 
 <div class="outer"> <div class="inner"> Some text in it <br />and some more <br/>and more </div> </div> 

注意:您可以使用表格...(为您节省一个元素),而不是使用内部div。

编辑

使用您的HTML(请注意,我已经添加了form标签)

 .outer { text-align: center; background: lightblue; } .inner { background: lightgreen; display: inline-block; text-align: left; } 
 <div class="outer small-3 small-centered text-left columns"> <form class="inner"> <input type="radio" name="lt_mc_ans" value="1" id="lt_mc_ans_1"><span> 1. </span> <label for="lt_mc_ans_1">I</label> <br> <input type="radio" name="lt_mc_ans" value="2" id="lt_mc_ans_2"><span> 2. </span> <label for="lt_mc_ans_2">rsr rs rsrs rsrs r rrrs</label> <br> <input type="radio" name="lt_mc_ans" value="3" id="lt_mc_ans_3"><span> 3. </span> <label for="lt_mc_ans_3">Very</label> <br> <input type="radio" name="lt_mc_ans" value="4" id="lt_mc_ans_4"><span> 4. </span> <label for="lt_mc_ans_4">She</label> </form> </div> 

如果将width属性更改为min-width属性,然后按如下所示设置width属性:

width: intrinsic;
width: -moz-max-content;
width: -webkit-max-content;

它应该表现出预期的效果。 有关“最大内容”选项的更多信息,请点击此处

编辑:使用您的html结构的codepen: 此处

您是否不仅可以将div设置为min-width,还可以将CSS的宽度设置为允许文本扩展的最小宽度?

暂无
暂无

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

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