Tips for aligning elements in the middle when hovering in CSS

As I dive into learning CSS, I am working on properly positioning elements. Currently, I have an HTML and CSS setup that creates a design resembling the Android robot. There's a functionality for the head where hovering over it changes its width to 300px. However, this causes the eyes to become uncentered. How can I keep the eyes centered during the hover event?

EDIT: Additionally, in the .eyes section of the CSS file, I noticed that simply using display: flex centers the eyes. I initially thought that I would need to add align_items: center to achieve the centering effect across the cross axis, but surprisingly, just setting display to flex did the trick.


                    h1 {
                        text-align: center;
                        font-family: 'Roboto', sans-serif;
                    }
                    
                    .robots {
                        display: flex;
                        flex-wrap: wrap;
                        justify-content: center;
                    }

                    /* Rest of the CSS code here */

                

                    <!-- Related HTML Code Here -->
                

Answer №1

To ensure your eyes are properly aligned, use margin instead of position for the left eye:

.left_eye, .right_eye { 
    width: 20px; 
    height: 20px; 
    border-radius: 15px; 
    background-color: white;
    margin: 0 auto; <-- automatically adjust horizontal margin
} 

By doing this, the eyes will remain centered even when the element's width is modified.

Answer №2

To implement this CSS code, you can easily adjust the width to suit your requirements.

.eyes{
width:200px;
margin:0 auto;
}

h1 {
  text-align: center;
  font-family: 'Roboto', sans-serif;
}

.robots {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.head,
.left_arm,
.torso,
.right_arm,
.left_leg,
.right_leg {
  background-color: #5f93e8;
}

.head {
  width: 200px;
  margin: 0 auto;
  height: 150px;
  border-radius: 200px 200px 0 0;
  margin-bottom: 10px;
}

.eyes {
  display: flex;
  align-items: center;
}

.head:hover {
  width: 300px;
}

.upper_body {
  width: 300px;
  height: 150px;
  display: flex;
}

.left_arm,
.right_arm {
  width: 40px;
  height: 125px;
  border-radius: 100px;
}

.left_arm {
  margin-right: 10px;
}

.right_arm {
  margin-left: 10px;
}

.torso {
  width: 200px;
  height: 200px;
  border-radius: 0 0 50px 50px;
}

.lower_body {
  width: 200px;
  height: 200px;
  /* This property is quite useful. Can you guess its function? */
  margin: 0 auto;
  display: flex;
  justify-content: center;
}

.left_leg,
.right_leg {
  width: 40px;
  height: 120px;
  border-radius: 0 0 100px 100px;
}

.left_leg {
  margin-right: 30px;
}

.left_leg:hover {
  -webkit-transform: rotate(20deg);
  -moz-transform: rotate(20deg);
  -o-transform: rotate(20deg);
  -ms-transform: rotate(20deg);
  transform: rotate(20deg);
}

.right_leg {
  margin-left: 30px;
}

.right_leg:hover {
  -webkit-transform: rotate(20deg);
  -moz-transform: rotate(20deg);
  -o-transform: rotate(20deg);
  -ms-transform: rotate(20deg);
  transform: rotate(340deg);
}

.left_eye,
.right_eye {
  width: 20px;
  height: 20px;
  border-radius: 15px;
  background-color: white;
}

.left_eye {
  /* These are new properties that may be unfamiliar to you. Explore CSS Tricks for more information! */
  position: relative;
  top: 100px;
  left: 40px;
}

.right_eye {
  position: relative;
  top: 100px;
  left: 120px;
}
`.eyes{
width:200px;
margin:0 auto;
}`
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

<h1>Robot Friend</h1>
<div class="robots">
  <div class="android">
    <div class="head">
      <div class="eyes">
        <div class="left_eye"></div>
        <div class="right_eye"></div>
      </div>
    </div>
    <div class="upper_body">
      <div class="left_arm"></div>
      <div class="torso"></div>
      <div class="right_arm"></div>
    </div>
    <div class="lower_body">
      <div class="left_leg"></div>
      <div class="right_leg"></div>
    </div>
  </div>
</div>

Answer №3

The positioning of the eyes is quite dynamic. Give this a shot, place the following in your CSS file:

.head:hover .right_eye {
  left: 170px;
}

.head:hover .left_eye {
  left: 100px;
}

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 are the steps to installing and utilizing the Chart.js package on your local machine?

I thought installing chart.js on my Raspberry Pi would be a simple task, but I seem to be struggling with it. Due to the nature of my project, I need to have it installed locally rather than relying on an online version. Following the usual steps, I navig ...

How can I show only the final four digits of an input field using Angular Material and AngularJS?

As a newcomer to Angular Material and Angular JS, I am striving to create an md-input field that displays only the last 4 digits in a masked format, such as "********1234". While my experience is currently limited to using md-input password fields where ...

Issue encountered while integrating crispy forms with Django and bootstrap

After developing a sign-in page for my blog using bootstrap and django, I decided to incorporate crispy forms. However, upon attempting to access the page, an error message popped up: TemplateDoesNotExist at /register/. Despite ensuring all redirects and U ...

Issue with JavaScript's variable scoping

After testing my application, I found that the following code was originally working: var htm = "<div> My content </div>"; $("#divprint").html(htm); window.setTimeout('window.print()', 4000); However, when I attempted to enclose it ...

Personalized FileInput within a card - Bootstrap 5

I am attempting to incorporate a custom file selection feature within a Bootstrap card: Here is my attempt: <style> label { cursor: pointer; } .custom-input-image { opacity: 0; position: absolute; z-index: -1; } </style> <div ...

What could possibly be the reason behind the initial box dropping?

Having trouble finding the right words to describe this? Take a look at it on codepen. http://codepen.io/rick-li/pen/JKEbw <div class="container"> <h1></h1> <div class="box"> <div class="sharePanel"> <div>content< ...

Struggling with implementing Mobile Navigation menu

I'm struggling to implement a mobile menu for my website. After adding the necessary code, when I view the page in a mobile viewport, all I see are two sets of periods ("..."). However, unlike in the code snippet provided, the list does appear on the ...

Looping through a jQuery script to add a class if a certain condition is met in another class

$(document).ready(function() { if ($("#grid .media-box").hasClass("brand1")) { $("#grid .media-box-content").addClass("brand01") }; } }); and in body looping div grid <div id="grid"> <?php foreach($data as $items) { ?> <div cl ...

Change the dropdown menu text to show the selected option text once the page has been redirected

Hey there, I am looking to dynamically update the dropdown text with the selected option after a page redirect and reload of the dropdown. Check out my code below: <div class="sorting-option"> <select id="selectdropdown" class="dropdown-selec ...

Display or conceal features in a django application for users depending on their permission levels

I run a Django application where users log in to access its features. However, I need to restrict certain users from accessing specific parts of the web app. Even though I have tried using permission_required, the tab still displays in the HTML. Is there ...

Discover the magic of using Polymer core-animated-pages transitions to create a stunning tile-cascade effect for your custom elements!

Trying to recreate the slide-up and tile-cascade transitions from this example using a snippet with the polymer designer tool. This time, custom elements are preferred over regular HTML tags. Custom elements have been created for each page and placed with ...

Using template expressions to access properties that contain spaces

Here is the code structure that I am working with: "name": { "age": [ { "data": { "how old": "23" } }, One of my JSON keys has a space in it. How can I access this pr ...

Display substitute text for the date input field

When using input types date and datetime-local, the placeholder attribute does not work directly. <input type="date" placeholder="Date" /> <input type="datetime-local" placeholder="Date" /> Instead, the ...

My content is being obstructed by a single-page navigation system

I attempted to create a simplified version of the issue I am facing. Basically, I am working on a header with navigation that stays at the top of the page while scrolling. The problem arises when clicking on a section in the navigation. The screen scrolls ...

Issues with uploading files

I am trying to implement a functionality where users can upload video, audio, images, PDFs, PowerPoint presentations, and Word files, and then have them saved into a directory. However, when I try to upload the files using my code, there are no errors but ...

Font size transition on pseudo elements is not functioning properly in Internet Explorer when using the "em" unit

When I hover over, the font awesome icon and text on this transition increase in size. All browsers work well with this effect except for IE 11. This example demonstrates the same transition using px (class test1) and em (class test2). While using px wor ...

Center the text within a span element in an inline-block container

I'm currently working on a website design that features a flat aesthetic. I have a header at the top and two blocks of different colors placed side by side underneath it. Initially, I attempted to use float left and right for positioning but was recom ...

CSS and jQuery UI URLs are not resolving properly in MVC framework after deployment

Basically, the issue is that the url for an image in jquery-ui.css file does not resolve once the site is deployed. The website is deployed under the default web site in IIS7, causing the browser console to look for the image in a different location than e ...

The span is unresponsive

When focusing on an input or checking its validity, the span should move up but it's not responding to any styles. <div class="login"> <span class="logtxt">Username or email</span> <input type=& ...

What steps can I take to make my animation work in the opposite direction as well?

I'm currently working with an angular slider that is set to TRUE/OPEN by default. The issue I am facing is that while I am able to slide it using angular animations in one direction, I am unable to see the transition when sliding it back. Any assistan ...