防止孩子拉伸父容器 [英] Prevent child from from stretching parent container

查看:24
本文介绍了防止孩子拉伸父容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个子元素的固定位置容器元素.两个孩子都包含文本.我希望其中一个孩子使用其内容动态设置容器的宽度.我希望另一个孩子的文本根据该宽度进行适当换行.

例如:

.container {位置:固定;}.裹 {背景:红色;}.拉紧 {背景:绿色;}

<div class="wrap">这篇文章很长很长

<div class="stretch">较短的文字<div>

在本例中,我希望容器的宽度与较短的绿色 .stretch div 相匹配.我希望红色的 .wrap div 具有相同的宽度,文本包裹在里面,例如:

解决方案

我想到的解决方案是:

  • div需要根据其内容拉伸其宽度 ->最大内容
  • 父元素的宽度需要尽可能缩小,这取决于它的内容 ->min-content

具有不同行为的解决方案代码:

.container {宽度:最小内容;边框:2px 纯蓝色;边距:5px;}.裹 {背景:红色;宽度:自动;/* 默认顺便说一句 */}.拉紧 {背景:绿色;宽度:最大内容;}

<div class="wrap">这篇文章很长很长

<div class="stretch">较短的文字

<div class="容器"><div class="wrap">较短

<div class="stretch">较短的文字

<div class="容器"><span class="wrap">较短</span><div class="stretch">较短的文字


您可以从这个答案规范.

<块引用>

I have a fixed-position container element with two children. Both children contain text. I want one of the children to dynamically set the width of the container with its content. I want the other child's text to wrap appropriate based on that width.

For example:

.container {
  position: fixed;
}

.wrap {
  background: red;
}

.stretch {
  background: green;
}

<div class="container">
  <div class="wrap">
    this text is very very long
  </div>
  <div class="stretch">
    shorter text
  <div>
</div>

In this example, I would like the container's width to match the shorter green .stretch div. I want the red .wrap div to have the same width, with the text wrapped inside, like:

解决方案

The solution's come up with me was:

The solution code with variant bahaviors:

.container {
  width: min-content;
  
  border: 2px solid blue;
  margin: 5px;
}

.wrap {
  background: red;
  width: auto; /* default btw */
}

.stretch {
  background: green;
  width: max-content;
}

<div class="container">
  <div class="wrap">
    this text is very very long
  </div>
  <div class="stretch">
    shorter text
  </div>
</div>

<div class="container">
  <div class="wrap">
    shorter
  </div>
  <div class="stretch">
    shorter text
  </div>
</div>

<div class="container">
  <span class="wrap">
    shorter
  </span>
  <div class="stretch">
    shorter text
  </div>
</div>


You can read more about min-content and max-content from this answer or the specification.

这篇关于防止孩子拉伸父容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆