Choose the element before and add a style effect with CSS

I'm trying to create a layout with 3 <div> elements in one horizontal line, each with a width of 33.33%. When hovering over one div, I want its width to expand to 50% while the other two shrink to 25%.

<div id="A"></div>
<div id="B"></div>
<div id="C"></div>

I have successfully applied this effect to div A:

#A:hover{width:50%}
#A:hover+#B
{width:25%}
#A:hover~#C
{width:25%}

It works as expected for A. However, when hovering over B:

#B:hover{width:50%}
#B:hover+#A
{width:25%}
#B:hover~#C
{width:25%}

B expands to 50% and C shrinks to 25%, but A remains at 33.33%. How can I resolve this issue?

Answer №1

When it comes to Css, there are no previous selectors.

  • By default, the width is set to 33.33%.
  • Upon hovering over the parent element, the width changes to 25%.
  • Hovering over the div inside further adjusts the width to 50%.

* {
  box-sizing: border-box;
}
.par {
  overflow: hidden; /* to clear floats */
}
.par div {
  width: 33.33%; /* default width */
  transition: .2s linear;
  border: 1px solid red;
  height: 100px;
  float: left;
}
.par:hover div {
  width: 25%; /* width when you hover on parent */
}
.par div:hover {
  width: 50% /* width when you hover on the element */
}
<div class="par">
  <div id="A">1</div>
  <div id="B">2</div>
  <div id="C">3</div>
</div>

Answer №2

Utilizing Flexbox can achieve this layout without the need for a parent selector:

* {
  box-sizing: border-box;
}
.container {
  width: 80%;
  margin: 1em auto;
  display: flex;
}
.item {
  height: 150px;
  border: 1px solid grey;
  flex: 1;
  transition: flex 1s ease;
}
.item:hover {
  flex: 0 0 50%;
}
<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></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

Updating .babelrc to include the paths of JavaScript files for transpilation

Using Babel, I successfully transpiled ES6 JavaScript to ES5 for the project found at I'm currently stuck on updating my .babelrc file in order to automatically transpile a specific ES6 file to a particular ES5 file. Can someone guide me on what cod ...

Removing elements from an array of objects using specific values stored in another array - JavaScript

I'm currently working on implementing a reducer in redux that can delete multiple items from the state based on an array of values. Let's say I have the following array: const idArray = ["935", "933", "930"]; My goal is to remove objects that ...

Accessing Facebook through Login with only a button visible

I need help with checking the user's login status on Facebook. I have implemented the code provided by Facebook, but all I see is the login button. How can I determine if the user is already logged in or not? function testAPI() { console.log(&apo ...

Run a PHP function using <button onclick=""> tag

Is it possible to trigger the execution of a PHP script when clicking an HTML button? I am aware that simply calling a PHP function directly from the button's onclick event like this: <button onclick="myPhpFunction("testString")">Button</butt ...

Is there a way to insert text onto an Isotope image?

I recently created a portfolio using Isotope and Jquery, but I am struggling to add descriptive text to my images without disrupting the layout of the portfolio. I have experimented with various options such as using position:relative for the images and p ...

JS unable to insert new row in table

I checked the input value before submitting it in the form and confirmed that it is correct, returning as a string.enter image description here const saveList = () => { const inputListNameText = inputListName.value; fetch('/api/lists' ...

The use of "app.use("*") appears to be triggering the function repeatedly

app.use("*", topUsers) is being invoked multiple times. The function topUsers is called repeatedly. function topUsers(req, res, next){ console.log("req.url", req.url) findMostUsefullReviewsAggregate(6) .then(function(aggregationResult){ ...

What is the best way to determine which CSS class is shown when the page is loaded using JQuery?

I am facing a dilemma with displaying my site logo. I have both an image version and a text version, and I want to choose which one to display based on the vertical position on the page and the screen width. <a class="navbar-brand" id="top-logo" href=" ...

Is it possible to serve CSS using relative paths that go beyond the URL root?

I've encountered a file path issue with my HTML and CSS files. My HTML file is located in: src/test/html/index.html And the corresponding CSS file is in: src/test/css/index.css In the HTML file, the CSS is linked using: <link rel="stylesheet" ...

Monitoring changes within a factory

Hey there! I've got this shared_service factory that's being used by my menu and other elements on the page. angular.module('shared_service', []). factory('Shared', function($scope){ var shared_service = { ...

Error Timeout Encountered by Langchain UnstructuredDirectoryLoader

I am facing an issue while trying to load a complex PDF file with tables and figures, spanning approximately 600 pages. When utilizing the fast option in Langchain-JS with NextJS Unstructured API, it partially works but misses out on some crucial data. On ...

What is the best way to incorporate the .top offset into a div's height calculation?

Looking to enhance the aesthetic of this blog by adjusting the height of the #content div to match that of the last article. This will allow the background image to repeat seamlessly along the vertical axis. I attempted the following code: $(document).re ...

Manipulating object properties within an array through iteration

Here is the array I am working with: var data = [ {"firstname":"A","middlename":"B","lastname":"C"}, {"firstname":"L","middlename":"M","lastname":"N"}, {"firstname":"X","middlename":"Y","lastname":"Z"} ]; I need to update the values for all keys - firstn ...

Having issues transferring the variable from JavaScript to PHP?

When attempting to pass a variable via AJAX request in JavaScript, I am encountering an issue where the variable is not being received in my PHP file. I'm unsure of where the problem lies. Can anyone help? JavaScript code var build = { m_count : ...

When a user clicks on a React listItem, the information for that specific item is displayed using

As a beginner in the coding world, I am currently learning about React and JSON. My project involves working on three interconnected panels. Specifically, I aim to showcase checklist answers on the third panel. First Panel: Displaying: All the ESN ("46 ...

Learn how to use Javascript and ASP.NET to refresh the parent page in Mozilla Firefox browser

The code window.opener.location.reload(); works well in Internet Explorer, but it doesn't refresh the parent page in Mozilla Firefox. Can someone please advise me on how to refresh the parent page in a way that is cross-browser compatible? Here is th ...

What could be causing my div to display a horizontal scrollbar in Firefox?

Here's a straightforward test scenario: <html> <body> <div style="border:2px solid black; overflow: auto;"> x </div> </body> </html> Upon rendering, a horizontal scrollbar appears! I was using F ...

Wait for the canvas to fully load before locating the base64 data in HTML5

Wait until the full canvas is loaded before finding the base64 of that canvas, rather than relying on a fixed time interval. function make_base(bg_img, width, height) { return new Promise(function(resolve, reject) { base_image = new Image(); base_imag ...

Create custom buttons in Material-UI to replace default buttons in a React modal window

How can I prevent overlay on material-ui's RaisedButton? When I open a modal window, the buttons still remain visible. Which property should be added to the buttons to disable the overlay? Any assistance from those familiar with material-ui would b ...

"JQuery encounters a parsing error while trying to process an XML

When I try to make an ajax request for an xml file, I encounter a parse error due to the presence of the xml declaration. Here is my AJAX request: <script> $(document).ready(function(){ $.ajax({ url: "/test/test.xml", ...