Issue with a input element having relative positioning within a flexbox

Objective: Aim to align the middle DIV (MIDDLE) within a flexbox row in the center.

Issue: The right element includes an input element with relative positioning. Consequently, the middle DIV element (MIDDLE) is no longer centered but instead shifted to the left.

I attempted changing the positioning to absolute. This successfully centers the element, but it restricts the movement of the input field.

const btnS = document.querySelector('.bg-search');  
let isOpen = false;
btnS.addEventListener('click', (e) => {  
  const searchBox = document.querySelector('.searchbox');
  const inputBox = document.querySelector('.searchbox-input');

  console.log(e.target, isOpen)
  if (isOpen === false) {
    searchBox.classList.add('searchbox-open');
    inputBox.focus();    
    isOpen = true;    
  } else {   
    console.log('close input')
    searchBox.classList.remove('searchbox-open');
    inputBox.dispatchEvent(new Event('focusout'));
    isOpen = false;
  }

});
* {
  margin:0;
  padding:0;
  box-sizing: border-box;
}
:root {
  --nav-height: 50px;
}
nav {
  height: var(--nav-height);
  z-index:13;
  background: green;
  padding: 0 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap:10px;
  z-index: 20;
  position: relative;
}
.body {
  background: gray;
  position: relative;
  dispyay: flex;
  flex-direction: column;
  height:100vh;
}

.searchbox {
  position:relative;
  min-width:50px;
  width:0%;
  height:50px;
  float:right;
  overflow:hidden;    
  -webkit-transition: width 0.3s;
  -moz-transition: width 0.3s;
  -ms-transition: width 0.3s;
  -o-transition: width 0.3s;
  transition: width 0.3s;
}

.searchbox-input {
  position: relative;
  top:0;
  right:0;
  border:0;
  outline:0;
  background:#dcddd8;
  width:100%;
  height:50px;
  margin:0;
  padding:0px 55px 0px 20px;
  font-size:20px;
  color: #000;
}
.searchbox-input::-webkit-input-placeholder {
  color: #000;
  opacity:0.8;
}
.searchbox-input:-moz-placeholder {
  color: #000;
  opacity:0.8;
}
.searchbox-input::-moz-placeholder {
  color: #000;
  opacity:0.8;
}
.searchbox-input:-ms-input-placeholder {
  color: #000;
  opacity:0.8;
}
.searchbox-open{
  width:100%;
}

.searchbox-icon,
.searchbox-submit {
  width: var(--nav-height);
  height: var(--nav-height);
  display:block;
  position:absolute;
  top:0;
  font-family:verdana;
  font-size:22px;
  right:0;
  padding:0;
  margin:0;
  border:0;
  outline:0;
  line-height:50px;
  text-align:center;
  cursor:pointer;
  color:#dcddd8;
  background:#172b3c;
}
<div class="body">


  <nav>    
    <div class="container bm-btn">
      LEFT
    </div>      
    <div>MIDDLE!!</div>
    
    <div>
      <form class="searchbox bg-search">
          <input type="search" placeholder="Search......" name="search" class="searchbox-input" onkeyup="buttonUp(this);" required>
          <input type="submit" class="searchbox-submit" value="GO">
          <!--button-- class="searchbox-icon">S</button-->
          <span class="searchbox-icon">S</span>
      </form>      
    </div>
  </nav>
  
</div>

Answer №1

After examining the code, it became clear that many attributes initially assigned to the parent element .searchbox should actually be moved to its child element .searchbox-input. In order to avoid altering the parent's width, I decided to transfer the animation functionality to the child element instead. By setting the position of .searchbox-input to absolute, any changes in its width would not disrupt the layout of other elements within the flexbox. Please review the updated implementation to see if this aligns with your requirements.

const btnS = document.querySelector('.bg-search');  
let isOpen = false;
btnS.addEventListener('click', (e) => {  
  const searchBox = document.querySelector('.searchbox');
  const inputBox = document.querySelector('.searchbox-input');

  console.log(e.target, isOpen)
  if (isOpen === false) {
    searchBox.classList.add('searchbox-open');
    inputBox.focus();    
    isOpen = true;    
  } else {   
    console.log('close input')
    searchBox.classList.remove('searchbox-open');
    inputBox.dispatchEvent(new Event('focusout'));
    isOpen = false;
  }

});
* {
  margin:0;
  padding:0;
  box-sizing: border-box;
}
:root {
  --nav-height: 50px;
}
nav {
  height: var(--nav-height);
  z-index:13;
  background: green;
  padding: 0 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap:10px;
  z-index: 20;
  position: relative;
}

.body {
  background: gray;
  position: relative;
  dispyay: flex;
  flex-direction: column;
  height:100vh;
}

.searchbox {
  position:relative;
  min-width:50px;
  height:50px;    
}

.searchbox-input {
  position: absolute;
  top:0;
  right:0;
  border:0;
  outline:0;
  background:#dcddd8;
  width:0%;
  height:50px;
  margin:0;
  padding:0px 20px 0px 20px;
  font-size:20px;
  color: #000;
  -webkit-transition: width 0.3s;
  -moz-transition: width 0.3s;
  -ms-transition: width 0.3s;
  -o-transition: width 0.3s;
  transition: width 0.3s;
}
.searchbox-input::-webkit-input-placeholder {
  color: #000;
  opacity:0.8;
}
.searchbox-input:-moz-placeholder {
  color: #000;
  opacity:0.8;
}
.searchbox-input::-moz-placeholder {
  color: #000;
  opacity:0.8;
}
.searchbox-input:-ms-input-placeholder {
  color: #000;
  opacity:0.8;
}
.searchbox-open .searchbox-input {
  width:15em;
}

.searchbox-icon,
.searchbox-submit {
  width: var(--nav-height);
  height: var(--nav-height);
  display:block;
  position:absolute;
  top:0;
  font-family:verdana;
  font-size:22px;
  right:0;
  padding:0;
  margin:0;
  border:0;
  outline:0;
  line-height:50px;
  text-align:center;
  cursor:pointer;
  color:#dcddd8;
  background:#172b3c;
}
<div class="body">


  <nav>    
    <div class="container bm-btn">
      LEFT
    </div>      
    <div>MIDDLE!!</div>
    
    <div>
      <form class="searchbox bg-search">
          <input type="search" placeholder="Search......" name="search" class="searchbox-input" onkeyup="buttonUp(this);" required>
          <input type="submit" class="searchbox-submit" value="GO">
          <!--button-- class="searchbox-icon">S</button-->
          <span class="searchbox-icon">S</span>
      </form>      
    </div>
  </nav>
  
</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

The resource being requested is missing the 'Access-Control-Allow-Origin' header - Issue with Pinterest OAuth implementation

While working on implementing OAuth for Pinterest, I successfully retrieved the access code. However, when attempting to perform a GET /v1/me/ request, I encountered an error in the Chrome console: XMLHttpRequest cannot load . No 'Access-Contro ...

Problem with sortable columns in DataTables

$(document).ready(function () { var dt = $('#example').DataTable({ "processing": true, "serverSide": true, "ajax": "api.php?t=clients", "columns": [{ "className": "details-control", ...

When using the setTimeout function to update the state, React useContext appears to be ineffective

As a newcomer to React, I have a question about refreshing the score in my card game within a forEach loop using setTimeout. While the state appears to update correctly, the DOM (Component overarching) does not reflect these changes. export function Refill ...

What is the best way to maintain parameters in PHP form code?

I am facing an issue with a script that needs to run with a specific parameter (for example, details.php?studentid=10325). The script contains a form with the following code snippet to send form data back to the current script. However, for some reason, t ...

The exported NextJS URL isn't functioning properly

Recently, I delved into the world of Next JS by following a tutorial on YouTube by Brad Traversy. In his guidance, I used next export to export the program and ran it using serve -s out -p 8000. While the page loads perfectly on localhost:8000, the issue a ...

Executing a JavaScript function using document.write()

When I try to click on the SWF part1 links within the document.write() function in order to call the openswf function, nothing happens. Here is my code: <html> <a href="#" onclick="Popup();">show popup</a> <script> functio ...

Encountering an error message stating "Unable to read property 'map' of undefined while attempting to create drag and drop cards

I have incorporated the library available at: https://github.com/clauderic/react-sortable-hoc The desired effect that I am aiming for can be seen in this example: https://i.stack.imgur.com/WGQfT.jpg You can view a demo of my implementation here: https:// ...

Issue: The object is unable to be executed as a function, resulting in the failure to return an array

Currently, I am extracting table values from the UI row by row. This involves clicking on each row and retrieving the corresponding data. exports.getTableData = function(callback){     var uiArray =[];     var count;         aLib.loadCheck(c ...

A guide to displaying API response data in a React JS application

As a beginner in react JS, I've encountered a persistent issue. Here is the code: import React from 'react'; class SearchForm extends React.Component { async handleSubmit(event){ event.preventDefault(); try{ const url ='/jobs/ ...

AJAX Post Request Function without Form That Does Not Reset

I am currently struggling with understanding the Ajax POST method. I am attempting to make an API request, and since the response has similar parameters, I decided to create a global function that can be used by other HTML/JS pages. However, I am aware tha ...

The issue arises when interfaces are extended by another interface

Is there a way to have classes that implement both the Observer and Comparable interfaces together? interface Comparable<T> { equals: (item: T) => boolean; } interface Observer extends Comparable<Observer> { notify: () => void } ...

Slide the first div upward to display the text in the second div when hovering over the first div

I'm facing an issue where a div needs to move upwards when hovering over it. To see an example, take a look at this JSfiddle. The desired outcome is as follows: As illustrated, the right div is the one being hovered. I have attempted to create this ...

CSS: Centralize content and use a div to hide images that overflow the container

I successfully centered my divs and images both horizontally and vertically using CSS: .center { height: 100% } .center-center { position: absolute; top: 50%; left: 50%; width: 100%; transform: translate(-50%, -50%); text-align: center; ...

Creating a spinning Cube with separate fields for x, y, and z rotation speeds: a step-by-step guide

After dabbling in Java, Visual Basic, HTML, and CSS, I'm now looking to create an interface featuring a central spinning cube with 3 fields to control its x, y, and z rotation speeds. Can you suggest which language would be the best fit for this proje ...

Issue with Anchor class in CakePHP where the variable $action is not defined

I'm struggling to apply a class to my anchor link when it is active. How should I define the $action variable in this case? Version: 4.2.9 Error: Undefined variable: action [ROOT\templates\layout\default.php, line 108] templates/lay ...

How can I use map functions to change the border color of specific items when clicked?

I have an array filled with various data. Here is how my Array looks like, const faqData = [ { q: "How Can We Help You?", a: "Find answers to our most frequently asked questions below. If you can't find what you need, pl ...

Ensuring the presence of a bootstrap angular alert with protractor and cucumberJS

I am currently utilizing protractor, cucumberJS, and chai-as-promised for testing. There is a message (bootstrap alert of angularJS) that displays in the DOM when a specific button is clicked. This message disappears from the DOM after 6000 milliseconds. ...

Hide the div element when the url contains the word 'word'

I did some research online, but I couldn't find any information on whether this is doable. I'm currently using IPBoard and after their latest IPS4 update, I'm facing an issue where I can't simply change the homepage anymore. Now, I have ...

File or directory does not exist: ENOENT error occurred while trying to scan 'pages'

Having trouble adding a sitemap to my nextjs app - when I go to http://localhost:3000/sitemap.xml, I get this error: Error: ENOENT: no such file or directory, scandir 'pages' https://i.sstatic.net/cxuvB.png The code in pages/sitemap.xml.js is a ...

CSS Grid having trouble with wrapping elements

Greetings to all, As a newcomer to the world of web development, I am currently exploring the wonders of the CSS grid tool. However, I have encountered a roadblock: My intention is for the cards to automatically flow one by one into the next row while ma ...