Positioning a display:table element with absolute precision

I need help creating text hints for input fields when they are focused. You can check out my progress here: http://jsfiddle.net/krpkm5dc/. I initially struggled with setting the max-width for an absolutely positioned element, but I discovered that using display: table solved the issue.

 <div class="wrapper">
    <input type="text">
    <div class="hint">
        Lorem ipsum
    </div>
</div>

.wrapper {
    position: relative;
    display: inline-block;
}
.hint {
    color: white;
    background: #333;
    position: absolute;
    top: 0;
    left: 100%;
    display: none;
    max-width: 200px;
}
input:focus ~ .hint {
    display: table;    
}

However, I encountered another challenge when trying to adjust the positioning of the hint to the right side.

.hint {   
    right: 100%;    
} 

If you take a look at this example here: http://jsfiddle.net/6vxye8q5/, you'll see that the right side doesn't align properly with the left side of the input field. Can anyone explain why this is happening?

Answer №1

If you are looking to match the width of the .hint element with the input field, here's how you can achieve that:

For positioning the .hint to the left of the input field, you can set offsets like left: -100% and right: 100%.

If you want the .hint to be on the right side of the input field, then adjust the offsets to right: -100% and left: 100%.

To gain a better understanding of why this method works, it is recommended to refer to the CSS specification regarding the computation of offsets and widths for absolutely positioned elements.

For more information: http://www.w3.org/TR/CSS2/visudet.html#abs-non-replaced-width

You can also utilize margin values to adjust the position of the .hint element either away from or slightly overlapping the input field based on your layout preferences.

To achieve a shrink-to-fit width for shorter hint texts, enclose the text in an element styled with display: inline-table, and modify the text-align property for .hint accordingly.

.showLeft {
  text-align: right;
}
.showRight {
  text-align: left;
}
.wrapper {
  position: relative;
  display: inline-block;
}
input:focus ~ .hint {
  display: block;
}
.hint {
  position: absolute;
  top: 0;
  display: none;
}
.tableit {
  display: inline-table;
  text-align: left;
  color: white;
  background: #333;
}
.showLeft .hint {
  left: -100%;
  right: 100%;
}
.showRight .hint {
  text-align: right;
  right: -100%;
  left: 100%;
}
<div class="showLeft">
  <div class="wrapper">
    <input type="text">
    <div class="hint">
      <div class="tableit">
        Lorem ipsum
      </div>
    </div>
  </div>
</div>
<br>
<div class="showRight">
  <div class="wrapper">
    <input type="text">
    <div class="hint">
      <div class="tableit">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean euismod bibendum laoreet. Proin gravida d... (The rest of the content has been truncated)
      </div>
    </div>
  </div>
</div>

Answer №2

When you mix display: table; and position: absolute;, things can get a bit weird. It's one of those quirks that doesn't seem to have a clear explanation (I even reported bugs to Chrome about it). Instead, try using display: block; for a smoother experience. Check out this JSFiddle example for reference.

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

Employing the Confirm() function within the onbeforeunload() event

Is there a way to prompt the user with a confirmation box before exiting a page using JavaScript? If the user clicks "OK", a function should be executed before leaving the page, and if they click "Cancel", the page should remain open. window.onbeforeunloa ...

Styles for Material UI 5 class names

After upgrading from Mui 4 to 5, I am facing a challenge in using class names effectively. While the SX property allows me to apply styles to individual components, I am struggling with applying the same class to multiple components. In version 4, my code ...

Have you ever wondered how the automatic video play on scroll feature works on Tiktok.com and YouTube shorts when using a mobile device?

My goal with React JS is to develop a website similar to Tiktok, where the video below will automatically play with sound as the user scrolls down. I attempted to set this up using window.addEventListener("scroll",...), but after looking into it further, ...

PHP not displaying Bootstrap input validation message set by JS

Currently, I am attempting to implement error messages using .setCustomValidity() and the .invalid-feedback class on an HTML form utilizing Bootstrap 4. Essentially, when the user validates the form, a JavaScript script assesses the inputs and if any erro ...

What impact do varying screen sizes have on the width of CSS?

Can someone explain what this CSS code actually does: .class { width: 800px; } I've noticed that on my laptop screen, the element appears to be exactly 800 pixels wide. However, when I view it on my tablet screen, it shows up as 1600 pixels wide. Th ...

The text consistently remains positioned to the right of my image

Photo Gallery Title Issue I'm working on a photo gallery project where I want to add titles underneath each image. However, I'm facing a problem where the title is appearing next to the image instead of below it. You can see the issue in this sc ...

A CSS3 property that does not have a vendor prefix, followed by properties that do have vendor prefixes

As discussed in a response on Stack Overflow, one reason for the necessity of vendor prefixes in CSS properties is to prevent web pages from breaking even if the final specification varies from the implementation by different browsers. In a recent reading ...

Apply pointer style to the CSS only when a division contains text

If there is plain text inside a div with class="x95qze", how can we add cursor:pointer only to the second div that contains the text Cursor pointer required here. The div with class="x95qze" will not change. The content of the div may ...

Sending Javascript Variable through Form

I'm a newcomer to JavaScript and struggling to solve a particular issue in my script. I need help passing the variable "outVal" to a PHP script when the submit form is clicked. The value of "outVal" should come from the "output" value in the script. I ...

Unable to view images on Wordpress theme

I am currently facing an issue where some images in my asset folder are not displaying properly when I convert my HTML/CSS/JS template to Wordpress. The main problem is with the image that should show up when you first visit the website. Below is the CSS c ...

When I incorporate a gradient, the background of my Bootstrap button flickers when clicked

I have implemented Bootstrap 4 with the following code snippet: <!-- Flickers on click --> <a href="javascript:void(0)" class="btn btn-primary">.btn .btn-primary</a> <!-- Does not flicker on click --> <a href="javascript:void(0 ...

Tips for enabling auto-scroll feature in MuiList

Currently, I am working on a chat window component that utilizes Material UI for styling. I expected that setting a height or max-height on either the MuiList or MuiBox encapsulating the list would automatically scroll to the new message when it's sen ...

Store a designated text into a MySQL database by extracting it from every file within a directory

I've encountered various methods for "crawling" websites, but none seem to fit my requirements. I am interested in being able to extract data from each file within an online directory and then store the extracted information into a MySQL database: h ...

The col-xl-6 in bootstrap is malfunctioning as it is not displaying the remaining portion of the content

When I use the code col-xl-6, the remaining portion stays blank and the next content displays on the next line. What could be causing this issue? <div class="raw"> <div class="col-12 col-lg-6"> <p>Lorem Ipsum is s ...

Styling Borders in CSS/HTML

Having an issue with the CSS on my website, specifically when hovering over links in the navigation bar. I'm trying to add a border around the link when hovered over, but it's causing the other links to shift position. Here's what I have so ...

jQuery Mobile persists in loading the initial page of a multi-page document after form submission

After searching extensively for an alternative to data-ajax="false" without success, I've found myself in a dilemma. In my Phonegap application, utilizing jQuery Mobile to submit a form requires running it through the standard submit function in jQuer ...

Show Firebase Function Output

After delving deeper into my readings and making more edits, I have come to realize that my main issue lies in how I am calling the function in calculator.component.ts Here is an updated look at my HTML code: app.component.html <div> <h1 alig ...

What is the best way to place an "Add row" button directly in front of every horizontal row border within a table?

I would like to create an HTML table where I can insert rows by clicking on a centered "insert row" button placed between each pair of rows. This will help in visually indicating where the new row will be added. Is there a CSS solution to achieve this lay ...

JavaScript validation for verifying phone numbers

Currently, I am facing an issue with my form that consists of three elements. Specifically, I am trying to implement phone number validation for the user's input. My aim is to display an alert box if the phone number field contains any characters othe ...

The jQuery offset() function is not functioning correctly due to an improper value

When specifying like this: <div id="Chart1"/> <div id= "Chart2"/> and attempting to get the offset top value ($("#Chart2").offset().top) of the second div, it does not take into account the previous div element. Sample link: However, if I s ...