What is the best way to expand a div in a downward direction exclusively?

My task involves a parent div containing a centered child div. My goal is to have the child div grow downwards only upon clicking it, not in both directions.

Initial state of the two divs:

https://i.sstatic.net/cWYyV.png

Outcome after clicking on div 2:

https://i.sstatic.net/QGSDJ.png

Desired result after clicking on div 2:

https://i.sstatic.net/iossE.png

let div2 = document.querySelector("#div2");
div2.addEventListener("click", e => {
  div2.style.height = "300px";
})
#div1 {
  height: 200px;
  width: 200px;
  outline: red solid medium;
  display: flex;
  justify-content: center;
  align-items: center;
}

#div2 {
  height: 100px;
  width: 100px;
  outline: blue solid medium;
}
<div id="div1">
  <div id="div2"></div>
</div>

Answer №1

One way to achieve this is by utilizing the position absolute property

let containerDiv = document.querySelector("#container-div");
containerDiv.addEventListener("click", event => {
  containerDiv.style.height = "300px";
})
#main-div {
position:relative;
  height: 200px;
  width: 200px;
  outline: red solid medium;
  display: flex;
  justify-content: center;
  align-items: center;
}

#sub-div {
    position:absolute;
  top:50px;
  height: 100px;
  width: 100px;
  outline: blue solid medium;
}
<div id="main-div">
  <div id="sub-div"></div>
</div>

Answer №2

This solution may seem a bit unconventional, but by adding an extra element, you can achieve the desired effect. Keep in mind that this method may not be optimal for responsiveness across different screen sizes.

let div2 = document.querySelector("#div2");
div2.addEventListener("click", e => {
  div2.style.height = "300px";
})
#div1 {
  height: 200px;
  width: 200px;
  outline: red solid medium;
  display: flex;
  justify-content: center;
  align-items: center;
}
#divc {
  height: 100px;
  width: 100px;
}
#div2 {
  height: 100px;
  width: 100px;
  outline: blue solid medium;
}
<div id="div1">
  <div id="divc"><div id="div2"></div></div>
</div>

Answer №3

const box = document.querySelector("#box");
// Store the initial height of the box
const initialHeight = (box.clientHeight);
box.addEventListener("click", e => {
  // Adjust the position and size of the box
  const transformVal = initialHeight / 2;
  box.style.transform = `translateY(-${transformVal}px)`;
  box.style.top = '50%';
  box.style.height = "300px";
})
#container {
  height: 200px;
  width: 200px;
  outline: red solid medium;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

#box {
  height: 100px;
  width: 100px;
  outline: blue solid medium;
  position: absolute;
}
<div id="container">
  <div id="box"></div>
</div>

Answer №4

To ensure that div1 grows with div2 and maintains the area around it, you can set the height of div1 to 100% and add padding for spacing.

#div1{
  height: 100%;
  width: 160px;
  padding: 40px;
  outline: red solid medium;
  display: flex;
  justify-content: center;
  align-items: center;
}

Answer №5

Consider experimenting with the transform-origin property, using the value "center top" on both the child element and the container if necessary. Visit this link for additional guidance!

Answer №6

The issue with using flex is that it automatically centers content, which may not always be desired. For instance, if you want the blue square to remain at the top of the container.

This code snippet eliminates the need for flex by centering the blue element through manual adjustments. It moves the element 50% from the top and side, then shifts it back by half its height/width using a transform property.

Furthermore, the element is set to position absolute to prevent it from affecting the size of its parent when it expands.

A CSS variable is employed to define the initial height, allowing for precise control over the positioning of the element.

let div2 = document.querySelector("#div2");
div2.addEventListener("click", e => {
  div2.style.height = "300px";
})
#div1 {
  height: 200px;
  width: 200px;
  outline: red solid medium;
  position: relative;
  --h: 100px;
  --w: 100px;
}

#div2 {
  height: var(--h);
  width: var(--w);
  outline: blue solid medium;
  top: calc((100% - var(--h)) / 2);
  left: calc((100% - var(--w)) / 2);
  position: absolute;
}
<div id="div1">
  <div id="div2"></div>
</div>

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

What steps do I need to take in order to create a histogram with perfect symmetry?

I am looking to create a unique JavaScript program that can generate a symmetric histogram resembling the image provided below: This program will prompt the user to input the number of bars they want to display and specify the character used to draw the b ...

Using gradients in the app bar with ReactJS and Material UI is not currently supported

Recently, I decided to create my own custom appbar for a personal project and opted to use the Erica One font. As it is still in its initial stages, there isn't much code written yet. However, I've encountered two issues related to linear and ra ...

Achieving cell merging in react-table can be accomplished by utilizing the appropriate

Currently, I am using react-table and have the need to combine cells in specific columns based on their content. Essentially, I want to remove the divider border between these merged cells. To give you a visual idea, this is how it currently looks like: h ...

What is the best way to save high-resolution images created with HTML5 canvas?

Currently, there is a JavaScript script being used to load and manipulate images using the fabricjs library. The canvas dimensions are set to 600x350 pixels. When smaller images are uploaded onto the canvas and saved as a file on disk, everything works c ...

Customize the toggle icon for the accordion in Framework7

I took inspiration from the custom accordion elements provided in the documentation and made some alterations to the icons. However, I'm facing an issue with getting the toggle functionality of the icons to work properly. My goal is to have a "+" dis ...

Struggle with Firefox: Table-cell with Relative Positioning Not Acting as Parent

Upon investigation, I have come across a unique layout issue that seems to only affect Firefox. It appears that elements with display:table-cell; do not act as the positional parent for descendants with position:absolute;. It is surprising to discover th ...

Javascript provides the ability to return a JSON object containing a specific function name

Currently, I am in the process of mastering AngularJS, and recently came across this code snippet: .factory('cribs',function(){ var data = [{ name: "jack", last: 'doe' },{ name: 'hazel&apos ...

Expanding the clickable area of a link using the CSS :before pseudo-element selector

I am currently working on a project involving an image slider and I am facing a challenge with the "previous" and "next" arrows. My goal is to have each arrow occupy half of the slider area, but adjusting padding or margins tends to change their position o ...

Am I on the right track in my understanding of how document and viewport relate to mouse position in JavaScript?

After reviewing responses from a previous inquiry, it is evident that both pertain to the x and y coordinates of mouse positions. In relation to the document and In relation to the viewport. I have delved into an article on QuirksMode, yet I feel ther ...

Using SQL to Insert Values into Select/Option

I am attempting to create a select form element with predetermined options. <select name="select1"> <option value="value1">Value 1</option> <option value="value2">Value 2</option> <option value="value3">Value 3 ...

The integration of AngularJS with a redirect feature is causing issues with sending JSON data to the database

I have encountered an issue when trying to send JSON data to a backend database. Everything works perfectly until I introduce a redirect within the newPost function using "$window.location.href = 'success.html';" Once the redirect is added, no da ...

Steps for implementing a conditional rendering in your codeHere is a

I've encountered an issue while attempting to implement conditional rendering. The error I'm getting is Element implicitly has an 'any' type because expression of type 'number' can't be used to index type 'types&apos ...

Exploring various templates with AngularJS Directives

Let's delve into a slightly complex topic, but I'll simplify it as much as possible for you. There is a directive in play: .directive('configuratorRows', function () { return { restrict: 'A', scope: { ...

Trouble with component not refreshing upon store modification in Vuex

Summary: If you prefer, I have a video detailing my issue: https://youtu.be/Qf9Q4zIaox8 Concern with Navbar Component Not Updating on Store Change. The issue I'm facing involves the Navbar component not updating when there is a change in the store. ...

Unable to retrieve private field using a public getter method through a proxy

When retrieving data from a VueX Module using a Getter, the Object is enclosed within a Proxy that triggers the following error: TypeError: attempted to get private field on non-instance when attempting to access a private property with a public getter. ...

JavaScript - Unable to Modify Select Value with Event Listener

It's interesting how I can change the selected option in a dropdown list using JavaScript without any issues. However, when I try to do the same thing within an event listener, the option does not seem to change. Here's the HTML code: <select ...

To what extent can the Vuetify data tables be customized?

https://i.sstatic.net/x4qhA.png I am currently working on replicating the layout shown in the image above. The table is already functional in my Vue project. The following code snippet represents the Vuetify datatable template in use: <v-card> ...

Should I utilize Next.js API route or communicate directly with Firestore from the client side?

Greetings, I am new to Next.js and have a few queries regarding utilizing Firebase authentication on both the client side and server side. My project is set up with Firebase admin and client SDKs, and I have a signup page where users provide their name, em ...

Exploring Array Iteration: Navigating through Arrays with the .map Method in React and Vue

I am currently using Vue after coming from a React background. In React, there is a method called .map that allows you to render a component multiple times based on the number of items in an array and extract data from each index. Here's an example: f ...

Getting rid of a texture in three.js

I am attempting to deallocate a texture once it has been loaded in three.js. The texture is loaded using var tex = THREE.ImageUtils.loadTexture("image.png"); and it is being displayed correctly. However, when I attempt to use: tex.dispose(); I consist ...