【问题标题】:Make CSS Max Width the width of an individual element?使 CSS Max Width 成为单个元素的宽度?
【发布时间】:2022-01-29 06:19:04
【问题描述】:

我正在尝试将整个 div 的最大宽度属性设置为其中一个元素的宽度,我该如何做到这一点?或者我根本无法做到这一点。

这是一个示例用例:

<div class="max-w-[610px]">
    <div class="mt-12 mb-12">
        <p class="mb-8">With RepoZoid, storing your own code is as easy as pie. Just add a new entry, paste your
            code in - and you're off to the races.</p>
        <p>It's as simple as 1, 2, 3 - with sharing options and more coming in the future!</p>
    </div>

    <div class="flex flex-row mb-3">
        <div class="grow">
            <input class="w-full text-[#9c9ea5] py-3 px-4 rounded-md" placeholder="Enter your email" type="email"
                name="emailinput">
        </div>

        <div class="pl-2">
            <button class="px-4 h-full rounded-md bg-[#6E6BFF] text-white">Sign Up to the Beta</button>
        </div>
    </div>

【问题讨论】:

    标签: javascript html css tailwind-css


    【解决方案1】:

    我对 Tailwind 不太熟悉,但我会给你一个纯 HTML/CSS 的解决方案。

    .parent {
      padding: 10px;
      background: yellowgreen;      
      display: flex;
      /* Add `flex-direction: column;` if you want each child to be in one-row */
      width: fit-content;
    }
    
    .child {
      width: 100px;
      height: 50px;
    }
    
    .child:nth-child(1) {
      background: red;
    }
    
    .child:nth-child(2) {
      background: blue;
    }
    <div class="parent">
      <div class="child"></div>
      <div class="child"></div>
    </div>

    如果您不想使用fit-content,您可以使用display: inline-block; 并从您的父级中删除width,如下所示:

    .parent {
      padding: 10px;
      background: yellowgreen;
      display: inline-block;
    }
    
    .child {
      display: inline-block; /* Make it `display: block;` if you want each child to be in one-row */
      width: 100px;
      height: 50px;
    }
    
    .child:nth-child(1) {
      background: red;
    }
    
    .child:nth-child(2) {
      background: blue;
    }
    <div class="parent">
      <div class="child"></div>
      <div class="child"></div>
    </div>

    另外,我会引用@voneiden in a similar question的评论;

    块元素将占用父级必须提供的水平空间,而inline-block 将占用显示内容所需的水平空间(除非被覆盖)。如果inline-block 大于父级,它将溢出。您可以通过设置width: fit-content 来创建块元素来评估内容宽度,但这与 IE 不兼容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-05
      • 1970-01-01
      • 1970-01-01
      • 2014-07-13
      相关资源
      最近更新 更多