Unable to align text within a DIV using CSS

Recently, I started learning jQuery and building my own website. You can find my project on JSFIDDLE. The issue I'm facing is that when hovering over a new div, the text extends beyond the borders of that div instead of staying within it. I've spent over an hour trying to fix this seemingly simple problem but haven't been successful. Any help would be appreciated.

Here's the code snippet:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8>
    <title></title>
    <script src="example.js"></script>
    <link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="box">
  <h2 id='name'> Karan Shah </h2>
  <div id='innerbox'><span><h4 id='emptyInfo'></h4></span><div>
  <script>
    $('#innerbox').hide();
  </script>
</div>

<script>
$('#name').css('color','black');
$('#name').css('text-align','center');


$(document).ready(function () {
    var originalText = $('#name').text();
    var tOut;
    $("#box").hover(
        function () {   
            tOut = setTimeout(function(){
                $('#innerbox').show('slow',function(){
                    $('#emptyInfo').fadeOut(400, function () {
                        $(this).text('Welcome to my website').slideDown().css('text-align','center');
                    }); 
                }); 
            },1000);        

        },
        function(){
            clearTimeout(tOut);
            $('#innerbox').hide('slow',function(){
                $('#emptyInfo').hide('slow');
            });     
        }
    );
});
</script>

</body>
</html>

The CSS styles used are:

#box {
    background-color: lightgrey;
    width: auto;
    padding: 25px;    
    margin: 25px;
}
#emptyInfo{
    font-size: 150%;
}

#innerbox {
    background-color: white;
    width: auto;
    height: 30px;
    border-radius: 10px;
    border : 1px;
    border-style: solid;
    border-color: darkgrey;
}

Answer №1

As emmanuel noted, Heading tags already have their own margins set by default. To fix this issue, simply add #emptyInfo { margin: 0; }.

If you're curious about what these default values are, you can refer to the specific default stylesheets of your browser. Check out this link for more information: How can I locate the default style sheet for a browser?

Keep in mind that HTML elements usually come with default values, so it's common for HTML/CSS authors to "normalize" their pages. This process is well explained on W3C's website: http://www.w3.org/International/questions/qa-html-css-normalization.

Answer №2

#container height needs to be adjusted dynamically. Check out the JSfiddle example

#container {
    background-color: white;
    width: 100%;
    height: auto; /*** Make sure this is set to adjust automatically */
    border-radius: 5px;
    border : 2px solid darkblue;
}

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 disappearance of the "Event" Twitter Widget in the HTML inspector occurs when customized styles are applied

Currently, I am customizing the default Twitter widget that can be embedded on a website. While successfully injecting styles and making it work perfectly, I recently discovered that after injecting my styles, clicking on a Tweet no longer opens it in a ne ...

Iterating through elements to set the width of a container

I am currently working on a function that dynamically adjusts the width of an element using JavaScript. Here is my JavaScript code: <script> $('.progress-fill span').each(function(){ var percent = $(this).html(); if(per ...

Positioning a button at the center-right

I'm currently in the process of creating a coming soon website, which you can find hosted here. However, I am having some trouble aligning the button correctly. My goal is to have it positioned to the right of the text field. How can I achieve this? ...

Issue with Ajax Form Handling

I am struggling to get my ajax form post working correctly. It seems like there might be an issue with the $.ajax lines in my code. When the code reaches the $.ajax portion, the console.log() function stops working and the form redirects normally to the aj ...

The table's pagination displays above, thanks to Tailwindcss

I'm facing an issue where the pagination is showing up above the table, but I was expecting it to be displayed after the table. It would be ideal if the pagination appeared right after the table when adding multiple rows. Check this link for more inf ...

Perform a Fetch API request for every element in a Jinja2 loop

I've hit a roadblock with my personal project involving making Fetch API calls to retrieve the audio source for a list of HTML audio tags. When I trigger the fetch call by clicking on a track, it always calls /play_track/1/ and adds the audio player ...

Incorporate the key as a prop within a Child Component in a React application

I am trying to display a list of elements in React, where the key of each element is used as an index in front of the item. However, when I try to access props.key, it just returns undefined. Does anyone have any suggestions on how to access the key proper ...

Struggling to Send Data and Generate a Calculated Value with Django

Hello, I am currently in the process of learning Django as a beginner. I have written some code that allows me to input data, but for some reason, I cannot successfully POST it to the database. I'm not quite sure where I've made an error. Model ...

Searching in real-time with ajax in CodeIgniter framework is a seamless and efficient process

I'm a beginner in CodeIgniter and eager to learn. Currently, I'm facing an issue where the data is not being populated on the search page. In the model: function fetch_data($query) { $this->db->select('*'); $this-> ...

Leveraging jQuery Datatables within the Alfresco 5 platform

Currently, I am encountering issues setting up the datatables plugin (a jQuery plugin that enhances HTML tables) on a surf page in Alfresco 5. In Alfresco 5, dojo is used as the base for certain components. I don't have a deep understanding of dojo, ...

Alert: React-Weather is causing an invalid element type in React

I am feeling overwhelmed. I have created a custom component called react-weather which has been installed using npm. Here is the code snippet for my self-written Weather.js component located in the src/components folder: import React, { Component } from & ...

What is the best way to send a List in the model as a parameter for an AJAX request?

I'm currently using MVC 4 ASP.net with Razor views and I have an issue with refining my search results using AJAX calls. The current approach involves creating methods in the controller that include all the search filters, which has resulted in a meth ...

Checkbox ensemble computes total score

I am currently working on a project that involves multiple checkbox groups, with each group containing 3 checkboxes labeled as (1, X, 2). My goal is to assign a value of 100% to each group, distributed evenly among the checkboxes within it. The distributio ...

Saving data returned by PHP in an AJAX call

I am currently working on storing data from an ajax (jquery) response into a variable so that I can utilize it later in my code. Below is the jQuery code snippet: $(document).ready(function () { $("#submitReg").click(function () { var email = $(" ...

What is the best way to format a time in a 12-hour clock using JavaScript?

Is it possible to create a timer that performs an action after 12 hours? I want the timer to start at 6am and end at 6pm, lasting for exactly 12 hours. Additionally, I'm interested in converting my current 12-hour clock into a 24-hour format. I am se ...

Create a Rest API and implement server-side rendering concurrently using SailsJs

I am exploring the potential of utilizing the SailsJs framework for nodeJs in order to create an application. Initially, my plan was to construct a REST API in Sails and utilize AngularJs for managing the Front-End. This API would also be beneficial for o ...

Using JavaScript's document.write method to display HTML code, along with a variable retrieved from a Flash application

Can I ask two questions at once? Firstly, how can I achieve the following? document.write(' <div id="jwplayer"> <center> <div id='mediaplayer'></div> <script type="text/javascript"> jwplayer('mediapl ...

Following the submission of a POST request, an error occurred stating: "Unable to assign headers once they have been sent to

I'm having trouble figuring out what's wrong with my code. Whenever I send a post request, I get an error message saying "Cannot set headers after they are sent to the client". My model includes a comment schema with fields for user, content, and ...

I can't seem to figure out why I keep encountering a runtime error whenever I attempt to create a basic route in the latest version of nextjs, version 13.5

Encountering an error while attempting to create a basic route in app/dashboard/page.tsx. The error message suggests that the contents are not a valid react component, even though they conform to valid react component syntax. Unhandled Runtime Error Erro ...

"Using the map function in Javascript to iterate through an array and then implementing

I am working on a script that involves an array of the alphabet along with two sets of values. The goal is to determine if a given value falls within the range specified by these two values and then print out the corresponding letter from the alphabet. H ...