Is it possible to set the maximum width of a specific element using CSS?

Is it possible to set the max width property of a whole div to match the width of one element inside it? If so, how can this be achieved?

Here is an example scenario:

<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>

Answer №1

I don't have much experience with Tailwind CSS, but I can provide a Pure HTML/CSS solution for you.

.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>

If you prefer not to use fit-content, you can opt for display: inline-block; and remove the parent's width like this:

.parent {
  padding: 10px;
  background: yellowgreen;
  display: inline-block;
}

.child {
  display: inline-block; 
  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>

Furthermore, I'd like to mention a valuable insight provided by @voneiden in a related discussion:

A block element takes up as much horizontal space as its parent allows, while an inline-block only occupies the necessary width for displaying its content (unless specified otherwise). If an inline-block exceeds the parent's width, it will overflow. To make a block element adjust to the content width, you can use width: fit-content, but keep in mind that this is not compatible with Internet Explorer.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Calculating the volume of an STL file mesh using three.js

I'm currently trying to figure out how to determine the volume of an STL file. I've successfully managed to obtain the dimensions of the model using var box = new THREE.Box3().setFromObject( mesh ); var sizes = box.getSize(); However, when it c ...

Merging scripts to minimize HTTP requests - The Takeover of the Body Swappers

For my website design, I've implemented the Invasion Of The Body Switchers script from brothercake.com. This script involves loading three separate js files in the header. I'm looking to optimize my site by reducing the number of HTTP requests a ...

Can you generate an image of text using unique unicode characters?

I am looking to create and display an image of text. Currently, I am experimenting with text2png: text2png('this string', {font: '14px Courier', bgColor: 'white'}) However, it appears that text2png is unable to handle unico ...

Step-by-step guide for making a CSS triangle design that is compatible across different browsers

Here's a common CSS code for creating a CSS triangle: display: inline-block; vertical-align: middle; content: " "; border-right: 4px solid transparent; border-left: 4px solid transparent; border-top: 6px solid black; width: 0; height: 0; Click here ...

Accordion feature that loads JSON data dynamically with AJAX

I am facing a challenge with my HTML structure and corresponding CSS styling. The HTML code includes an accordion container with multiple sections that can be expanded or collapsed. <div class="accordion-container"> <ul class="accordion"> ...

Prevent clicking on form until setInterval has been cleared using React useEffect

Here is a link to a sandbox replicating the behavior: sandbox demo I have integrated a hook in a React component to act as a countdown for answering a question. React.useEffect(() => { const timer = setInterval(() => { setTimeLeft((n ...

Set a controller variable equal to a value assigned to a JavaScript variable within a view

As a newcomer to CodeIgniter and JavaScript, I am facing the challenge of assigning a value from a variable created in JavaScript in my view to a variable in my controller. Can someone guide me on how to achieve this? The main objective is to validate an ...

Struggling to construct a dynamic table from JSON data using JavaScript

I'm struggling to dynamically generate a table from JSON data using JavaScript. Despite trying multiple methods, I have not been able to achieve the expected results. My goal is to populate a table based on JSON data in a dynamic manner, but so far, m ...

Obtaining the jqXHR object from a script request loaded within the <head> tag using the <script> tag

Is it possible to retrieve the jqXHR object when a script loaded from a script tag within the head tag? function loadScript(url){ const script = document.createElement("script"); script.src = url; // This line will load the script in the ...

ReactJS select component failing to display accurate current value

My React custom Select component is not updating the selected value properly. Even though I select a new value from the dropdown, it still shows the old value. For example, if I choose '4' from the options, the handleChange function will receive ...

Utilizing custom filters to navigate through nested ng-repeats

My goal is to achieve a specific behavior by using custom filters. I am working on creating a unified search bar that will display entire group names with all failing students, as well as group names with only the matching students. If you want to see the ...

When attempting to execute the "npm run prod" command, the terminal displays the error message "error:03000086:digital envelope routines::initialization error."

In my current project, which combines vue and laravel, I encountered an issue when trying to run the production command: npm run prod The error message that appeared was: opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization ...

Problems with Angular UI Router: Functions not functioning properly within the template

Currently, I am delving into the realm of Angular UI Router in order to effectively manage different sections of my application. If you'd like, check out this plunkr (http://plnkr.co/edit/KH7lgNOG7iCAEDS2D3C1?p=preview) Here are some issues that I&a ...

Using Tailwind classes as a prop functions correctly, however, it does not work when directly applied

Here's a component snippet I'm working on: export const TextInput = ({ label, wrapperClassName = "", inputClassName = "", labelClassName = "", placeholder = "", ...props }: InputProps & Fiel ...

Multiplication cannot be performed on operands of type 'NoneType'

Hello everyone, I am attempting to calculate the unit price and quantity from this table using the following model: class Marketers(models.Model): category =models.ForeignKey(Category, on_delete=models.CASCADE, null=True) name =models.CharField(max ...

What is the best way to change the text within the first tag of an HTML markup using either jQuery or basic JavaScript?

My task involves dealing with an array of markup strings, similar to: const items = [ '<p class="item">text</p>', '<h1>hello</h1>', ]; I am looking for a way to replace the text content within the ...

Ways to streamline redundant code by creating a higher order function that accepts different parameter types in TypeScript

Recently, I've been exploring the idea of refactoring this code into a higher order function using TypeScript to enhance its cleanliness and reusability. However, I'm facing quite a challenge in getting it to work seamlessly. import { DocumentDef ...

Embracing the use of paragraph tags within tweets on a webpage

For a project on freecodecamp.com, I created a quote machine where you click a button to get a random quote and then have the option to tweet it using the "Tweet It" button. However, I encountered difficulty in getting the quote to display properly in the ...

Centered buttons placed right next to each other

Having trouble getting my buttons centered and aligned side by side on the screen. I've managed to achieve one or the other but not both simultaneously. Currently, the buttons are next to each other but positioned at the top left corner of the screen. ...

Looking for assistance in determining a solution for progress bar implementation

Currently, I am developing a simple application using web technologies like HTML, CSS, and jQuery Mobile. This app enables me to create goals and save them to a listview using the <li> element. Every <li> representing a goal will have an assoc ...