Placing a button above another element using CSS styled components

I'm attempting to make a button overlap and be positioned in a specific location on top of a search bar. The current appearance is not what I desire, as the button seems to shift back to its original position when adding a :hover element after applying transform: translateX().

https://i.stack.imgur.com/xhF2t.png

However, this is how I want it to look.

https://i.stack.imgur.com/ktC3e.png

Below is the CSS code I am using with styled components:

const Button = styled.button`

    display:block;
    width:40px;
    height:40px;
    /* line-height:80px; */
    border: none;
    border-radius: 50%;
    color:#f5f5f5;
    text-align:center;
    text-decoration:none;
    background: #0072FF;
    box-shadow: 0 0 3px gray;
    font-size:20px;
    font-weight:bold;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    transform: translateX(-180%);
    
    &:hover {
        outline: none;
        transform: scale(1.05);
    }
`;

const Input = styled.input`
    color: inherit;
    border : none;
    background: none;
    padding-left: 10px;
    width: 100%;

    &:focus {
        outline : none;
    }
`;

const Form = styled.form`
    background-color : white;
    border-radius : 7px;
    height: 5%;
    width: 75%;
    align-items: center;
    display: flex;
    transition: all .3s;
    margin-left: 6%;
`;

const Img = styled.img`
    height: 15px;
    width: 15px;
    margin-left: 10px;
`


Here are the components I am utilizing:

import React from 'react'
import NewChat from '../newChat/newChat';
import { Input, Form, Img } from './searchBar.elements';
function SearchBar() {
    return (
        <Form>
            <Img src={require("../../../../assets/img/search.svg")} />
            <Input placeholder="Find people and conversations" />
            <NewChat />
        </Form>
    )
}


export default SearchBar;
import React from 'react'
import { Button} from './newChat.elements';
import plus from '../../../../assets/img/plus_button.svg';

function NewChat() {
    return (
        <div>
            {/* <img src={require("../../../../assets/img/plus_button.svg")} /> */}
            <Button>
                <svg
                    width="24"
                    height="24"
                    viewBox="0 0 24 24"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                >
                    <path
                        d="M12 4C11.4477 4 11 4.44772 11 5V11H5C4.44772 11 4 11.4477 4 12C4 12.5523 4.44772 13 5 13H11V19C11 19.5523 11.4477 20 12 20C12.5523 20 13 19.5523 13 19V13H19C19.5523 13 20 12.5523 20 12C20 11.4477 19.5523 11 19 11H13V5C13 4.44772 12.5523 4 12 4Z"
                        fill="currentColor"
                    />
                </svg>
            </Button>
        </div>
    )
}

export default NewChat;

Answer №1

For my issue with getting a button to overlap and be positioned at a specific place on a search bar, one solution could be to utilize the CSS properties position: relative on the parent component (Form) and position: absolute on the Button. By doing this, the parent component acts as a reference for the absolute positioning of the button, allowing you to use properties like Left, Top, Right, Bottom to adjust its position accordingly.

const Form = styled.form`
  ...otherProperties,
  position: relative;
`;

const Button = styled.button`
    ...otherProperties,
    position: absolute;
    right: 180px; // example
    top: 50px; // example
`;

As for the issue where the button moves back to its original position when hovering due to the transform: translateX() property, this happens because the transform property is being altered within the button's styling.

const Button = styled.button`
  display:block;
  width:40px;
  height:40px;
  /* line-height:80px; */
  border: none;
  border-radius: 50%;
  color:#f5f5f5;
  text-align:center;
  text-decoration:none;
  background: #0072FF;
  box-shadow: 0 0 3px gray;
  font-size:20px;
  font-weight:bold;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  transform: translateX(-180%); // The transform property here is translateX //

  &:hover {
      outline: none;
      transform: scale(1.05); // Now the transform property becomes scale on hover //
`;

To resolve this issue, it's important to retain the previous transformation while adding new transformations in the :hover state.

&:hover {
  outline: none;
  transform: translateX(-180%) scale(1.05);
}

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

Conceal navigation options on smaller screens and enable drop-down menu functionality with Bootstrap 3

With the usage of Bootstrap 3, I have successfully hidden two menu items when the screen is resized. However, these items still appear in the drop down menu that appears on the top left (with three bars) when the screen size is reduced. Is there a way to k ...

Guide to changing the status code to 404 for a 404-page in Next.js

I have been trying to figure out how to set a 404 status code for the 404-page in Next.js. The response I received stated that the status code is already 404 by default, but upon closer inspection, it seems that all bad requests are returning a 404 status ...

Is there a way to customize the primary column in Material-table?

I am utilizing the Material-table and I am in need of rearranging the column index to be at the end of the table as the default position for this column (actions) is at the beginning. Here is the code snippet for the table: <MaterialTable title=" ...

Modify the CSS of the gauge element without causing any issues

I am facing an issue while trying to resize this gauge element. Whenever I attempt to modify the container class to make it smaller, the entire gauge ends up distorting. Changing the position to relative seems to cause glitches at the edge of the gauge. An ...

What's the most effective method for implementing a stylesheet through Javascript in a style switcher?

I've been tackling the challenge of creating a style switcher for my website. Through utilizing .append() and if and else statements, I managed to make it work successfully. Take a look at the code below: HTML <select name="active_style" id="lol" ...

The elements from base.html and the extended page are now placed on separate rows rather than on the same row

I'm relatively new to HTML, Jinja, and CSS and have been playing around with creating a webpage that retrieves data from a sqlite3 database. As of now, I am facing some challenges regarding formatting. To assist with table formatting and overall aest ...

is it possible to adjust the height of a tableRow in mui?

I recently created a table component using Mui. I've been attempting to adjust the height of the tableRows, but so far I haven't had any success. Below is my code snippet: import React, { memo } from "react"; import { ActionItemType, ...

Is there a way to confirm if all div elements have a designated background color?

I have a scenario where I have dynamically added several divs with a specific class to my webpage. These divs change color when the user hovers over them. I am trying to trigger a specific function once the last div has been set to a particular backgroun ...

Unlock the Power of Rendering MUI Components in ReactJS Using a For Loop

Hey there! Hope everything is going well. I've been working on a fun project creating an Advent/Chocolate Box Calendar using ReactJS. One challenge I'm facing is figuring out how to iterate over a for loop for each day in December and render it ...

How to use a loop to alternate CSS classes in HTML?

Here is a sample code using a while loop: while($fetch = $stm->fetchAll()) { echo '<tr class=""'>; echo '<td>' . $fetch['name'] . '</td>'; echo '</tr>'; } I want to ...

Steps for deactivating AMD on four files and sequentially loading them using webpack

I am facing an issue where I need to disable AMD on 4 files and ensure that video.js is loaded before the other 3 files, as they are dependent on it. My attempt to achieve this in webpack.config.js was unsuccessful: const path = require('path') ...

Can you show me how to create a React Testing Library test that verifies how hovering changes the style of components?

I am currently testing my application and came across a peculiar issue. As I was attempting to test whether a row in my dropdown component triggers an effect on hover, I noticed that I was unable to verify elements based on their background color. Even wh ...

What is the best way to make a CSS change triggered by a onScroll() event stay in place permanently?

I need a div element to be displayed as a "scroll back to top" button on my webpage when the user has scrolled past a certain point. To achieve this, I am using the JavaScript code provided below: $(document).ready(function() { $(window).scroll(functio ...

Exploring the world of colored tab links in CSS

Check out this code: <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>My Unique Page</title> <link rel="stylesheet" href="http://code.jquery.com/ui/1.8.3/themes/base/jquery-ui.css" /> ...

Why does React / NextJS throw a "Cannot read properties of null" error?

In my NextJS application, I am using useState and useEffect to conditionally render a set of data tables: const [board,setBoard] = useState("AllTime"); const [AllTimeLeaderboardVisible, setAllTimeLeaderboardVisible] = useState(false); const [TrendingCreat ...

Creating an HTML element that can zoom, using dimensions specified in percentages but appearing as if they were specified in pixels

This question may seem simple, but I have been searching for an answer and haven't found one yet. Imagine we have an HTML element with dimensions specified in pixels: <div style="width:750px; height: 250px"></div> We can easily resize i ...

Deactivate the focus state when hovering over different items in the navigation bar

Currently facing an issue with my Navbar items having underline animation on hover. Once clicked, the animation persists. However, when hovering over a neighboring navbar item, the underlines appear next to each other, creating the illusion of one long lin ...

Sending an array of files to an express backend: A step-by-step guide

I am having an issue sending an array of images to my backend for upload using multer-s3. The process involves sending the images from a React frontend to a Node Express backend. Once submitted from the frontend, the images are formatted as follows: image ...

Bootstrap 3's Clear:Left Media Query Feature

Bootstrap is being used, and there is a div with col-xs-12, col-sm-6, col-md-4 classes. Task : To add a clear on every 1 item for col-xs-12, add a clear on every 2 items for col-sm-6, and clear on every 3rd item for col-md-4. The current code only s ...

Struggling to update the previousCode state with the useState hook in React

I'm having trouble understanding why the state isn't changing when using setPreviousCode in React and JavaScript. I'm trying to store the previously scanned text in the variable previousCode. import React, { useEffect, useState } from " ...