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

Achieve automatic updates on React + Django without the need to execute "npm run build" every time

I've managed to integrate my Django + React app successfully for the most part. However, I find it tedious that every time I need to make changes to my React code, I have to stop Django from running and then run npm run build again. Despite reading d ...

What could be causing my Styled Components not to display the :before and :after pseudo elements?

When attempting to use the content property in a :before or :after pseudo element, I am encountering a rendering issue. Here is a simplified version of the component: import React from 'react'; import PropTypes from 'prop-types'; import ...

Should the JSON data in an ASP.NET React application be serialized and normalized on the client-side or server-side?

Currently, I am in the process of developing a asp.net react application. Up until now, I have successfully completed the serialization and normalization of nested data on the client-side using normalizr. However, I am considering whether it would be more ...

Standardize API data for utilization in Redux

I have an API that provides the following data: const data = { id: 1, name: 'myboard', columns: [ { id: 1, name: 'col1', cards: [ { id: 1, name: 'card1' }, { id: 2, name: 'card ...

The text content is not in alignment with the server-rendered HTML for translation purposes with i18n

I have successfully implemented i18n in my Next.js project. The folder structure for my locales is as follows: public/locales/en/translation.json and public/locales/fr/translation.json The error I am encountering is: Uncaught Error: Text content does n ...

Incorporate create-react-app with Express

Issue - I am encountering a problem where I do not receive any response from Postman when trying to access localhost:9000. Instead of getting the expected user JSON data back, I am seeing the following output: <body> <noscript>You need to ...

Using the Drupal Colorbox module with Internet Explorer

This problem has been driving me crazy! I'm struggling to make Colorbox show the borders correctly in IE7 (and even in IE6, but I'll settle for just IE7 at this point!). You can check out the issue here. When you click on a picture in the galler ...

Guide on retrieving the initial value from a map in a React application

In my React project, I am working with a map that has string keys and values. Here's an example: let map = new Map(); map.set("foo", "bar"); map.set("foo-bar", "bar-foo"); What is the best way to retrieve the first value from this map? ...

The function this.client.defaultMutationOptions does not exist in the react-query, pocketbase, and nextjs libraries

I am currently following a tutorial on using Pocketbase with NextJS, but the video I'm watching uses create-react-app. This means I have to make some adjustments as I go along. It has been an interesting experience, but I have hit a roadblock and my u ...

Tips for overlaying text on the background in Next.js:

I'm currently working on creating an image element with overlay text. Check out my jsx code below: <div className={styles.img}> <img src={src} alt="" /> <p>{`(${size})`}</p> </div> And here is t ...

Error message indicating that the event "OnkeyDown" is not in sync within the React application

Hey everyone! I'm a beginner in web development and I'm struggling to understand why the event "OnKeyDown" is triggered the second time. My task involves changing (increasing, decreasing) parts of a date (day, month, year, hour, minutes, seconds) ...

Adjusting column widths in Material-Table: A guide to resizing columns

I am currently using the Material Table library, recommended by Google Material UI as a top data table library. I am facing some issues related to configuring the width of columns in this library. The column's `width` property seems to be functioning ...

Nested React Components in React Router Components

class AppRoutes extends Component { render () { return ( <Suspense fallback={<Spinner/>}> <Switch> <Route exact path="/" component={ HomePage } /> <Route exact path="/acti ...

I am unable to produce sound by clicking on the drum machine

My goal is to develop a basic react drum machine project that I discovered on freecodecamp. The objective is to display 9 drumpads and trigger sound upon clicking. Update: I have successfully rendered all the keys but I am facing issues with the function ...

Is it possible to optimize the performance of my React and TypeScript project with the help of webpack?

I am working on a massive project that takes 6 to 8 minutes to load when I run npm start. Is there a way to speed up the loading process by first displaying the sign-in page and then loading everything else? ...

Deliver JSX components that match one or more keys in the array of strings

Seeking assistance and guidance here. It seems like I might be overlooking something obvious. I am attempting to create a component that accepts either a string or string Array string[] as a property. const ComponentThatReturnsElement = (someElementName) = ...

Unexpected Token < in Jest/Enzyme testing for SVG Sprites

I'm encountering an issue while attempting to create a snapshot test using Jest and Enzyme on a component that utilizes SVG sprites. The package I am using is svg-sprite-loader, which can be found at: https://github.com/kisenka/svg-sprite-loader Bel ...

What steps can I take to ensure that the content remains intact even after the page is

Hey there, I hope you're having a great start to the New Year! Recently, I've been working on creating a calculator using HTML, CSS, and JavaScript. One thing that's been puzzling me is how to make sure that the content in the input field do ...

The navbar expands in height when resized

I've been working on creating a responsive navbar, but I'm facing an issue where the height of the bar doubles between phone screen size and full window size. Despite trying various Bootstrap classes, I haven't had any success in fixing this ...

Is there a way to align the height of a standard column with the ng-include section to ensure a cohesive page display?

I have been working on my Angular app and have implemented ng-include to dynamically add content to a template within the page. The issue I'm facing is that this specific area ends up being longer than both the html and body elements where it resides. ...