Achieving the perfect alignment: Centering a paragraph containing an image using JQuery

I need help centering the background image of my <p> tag on the webpage.

Script

$(function() {
    $('ul.nav a').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollLeft: $($anchor.attr('href')).offset().left
        }, 1000, "easeInOutExpo");
        event.preventDefault();
    });
    // $("#logo") = my <p> tag containg the background image
    var imgTop = ($(window).height() - $("#logo").css("height")) / 2;
    var imgLeft = ($(window).width() - $("#logo").css("width")) / 2;

    $("#logo").css({
        "top": imgTop,
        "left": imgLeft
    });

    setInterval(function() {
        $("#logo").fadeTo(2000, 0.7).fadeTo(2000, 1);
    }, 0);
});

CSS

*{
    margin:0;
    padding:0;
}

body{
    background: #100061;
    font-family:Georgia;
    /*font-size: 34px;*/
    letter-spacing:-1px;
    width:16000px;
    position:absolute;
    top:0px;
    left:0px;
    bottom:0px;
    overflow: hidden;
    height: 100%;
}

.section{
    margin:0px;
    bottom:0px;
    width:4000px;
    float:left;
    height:100%;
}
.section h2{
    margin:50px 0px 30px 50px;
}

.section p{
    margin:20px 0px 0px 50px;
    width:600px;
}

.section ul{
    list-style:none;
    margin:20px 0px 0px 300px;
}

#logo{
    width: 500px;
    height: 194px;
    position: absolute;
    top: 0;
    left: 0;
}

HTML

<div class="section black" id="home">
    <img src="images/logo.png" id="logo" />
    <ul class="nav">
        <li>
            <a href="#home">Home</a>&nbsp;&nbsp;
            <a href="#aboutUs">About Us</a>&nbsp;&nbsp;
            <a href="#contactUs">Contact Us</a>&nbsp;&nbsp;
            <a href="#products">Products</a>&nbsp;&nbsp;
        </li>
    </ul>
</div>
<div class="section white" id="aboutUs">
    <h2>About Us</h2>
    <p>
        ‘A fathomless and boundless deep,
        There we wander, there we weep;
        On the hungry craving wind
        My Spectre follows thee behind.
    </p>
    <ul class="nav">
        <li>
            <a href="#home">Home</a>&nbsp;&nbsp;
            <a href="#aboutUs">About Us</a>&nbsp;&nbsp;
            <a href="#contactUs">Contact Us</a>&nbsp;&nbsp;
            <a href="#products">Products</a>&nbsp;&nbsp;
        </li>        
    </ul>
</div>
<div class="section black" id="contactUs">
    <h2>Contact Us</h2>
    <p>
        ‘He scents thy footsteps in the snow
        Wheresoever thou dost go,
        Thro’ the wintry hail and rain.
        When wilt thou return again?
    </p>
    <ul class="nav">
        <li>
            <a href="#home">Home</a>&nbsp;&nbsp;
            <a href="#aboutUs">About Us</a>&nbsp;&nbsp;
            <a href="#contactUs">Contact Us</a>&nbsp;&nbsp;
            <a href="#products">Products</a>&nbsp;&nbsp;
        </li>
    </ul>
</div>
<div class="section white" id="products">
    <h2>Products</h2>
    <p>
        ‘He scents thy footsteps in the snow
        Wheresoever thou dost go,
        Thro’ the wintry hail and rain.
        When wilt thou return again?        
    </p>
    <ul class="nav">
        <li>
            <a href="#home">Home</a>&nbsp;&nbsp
            <a href="#aboutUs">About Us</a>&nbsp;&nbsp;
            <a href="#contactUs">Contact Us</a>&nbsp;&nbsp;
            <a href="#products">Products</a>&nbsp;&nbsp;
        </li>
    </ul>
</div>
<!-- The JavaScript -->
<script type="text/javascript" src="jquery.min.js"></script>        
<script type="text/javascript" src="jquery.easing.1.3.js"></script>
<script type="text/javascript" src="script.js"></script>

Fiddle

Answer №1

To ensure that an image element within a paragraph does not disrupt the content of the paragraph, you can use CSS to position the images accordingly: p img{ position: absolute; top: 50%; left: 50%; margin: -75px 0 0 -75px; float: left; }

To position the image absolutely, the container should be relatively positioned using position: relative. Here is an example: p{ height: 180px; width: 40%; position: relative; border: 1px solid red; }

Here is the HTML markup:

<p> 
    <img src="http://placekitten.com/150/150" alt="adorable kitten" />
</p>

Alternatively, a more efficient method would be to display the image using CSS:

background: url(http://placekitten.com/150/150) no-repeat center center;
. This simplifies the markup as follows:

<div id="logo"></div>

The CSS for the div element: #logo{ background: url(http://placekitten.com/150/150) no-repeat center center; height: 180px; width: 40%; border: 1px solid blue; }

You can also view this on http://jsfiddle.net/Er2Tw/

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

Showing content based on the route - Angular

I'm struggling to hide the navbar based on a specific route in my application. I have managed to subscribe to the route changes, but I am having difficulty changing the display property accordingly. Here is what I have so far: export class AppCompo ...

Connecting a specific entry in a data table with a corresponding web address

I have been working on a vue component that utilizes vue-tables-2. You can find the functioning example here. My goal is to link the edit href url to the entire row rather than just the edit cell. I attempted to achieve this using vanilla javascript by a ...

align the p tag vertically next to the image

I'm struggling to get a p tag vertically aligned next to an image. The issue is that only the first line of text aligns properly. How can I make the text in the p tag wrap around the image while maintaining vertical alignment? Here is the HTML code: ...

Discovering nested documents in MongoDB using JavaScript

How to find nested data in MongoDB with the following collection: { "_id": { "$oid": "585b998297f53460d5f760e6" }, "newspaper": { "playerID": "57bffe76b6a70d6e2a3855b7", "playerUsername": "dennis", "player_newspaper": "{\"ID\":\" ...

What is the best way to activate ui-sref in an AngularJS unit test?

Currently I am conducting a test on an AngularJS view. The code sample contains some non-standard helpers, but they should not affect the specific functionality being tested. Below is the view (written in Jade): #authentication-options button#sign-up(u ...

Create static HTML files using an Express server

Recently, I developed a nodejs web project using express-js and ejs. However, upon further reflection, it occurred to me that hosting it as static html files on Netlify might be more cost-effective than running it as a nodejs app on Heroku. Since the data ...

Present pop-up messages in the most sophisticated manner

I have successfully created an AngularJS app that is functioning well. Now, I am faced with the challenge of displaying different pop-ups based on specific conditions being met. I am unsure of the best approach to take. Currently, I am considering two op ...

Utilizing JavaScript and jQuery libraries in conjunction with periods

I am a bit puzzled about when to include the period before referencing class names. For instance, in this code snippet, why is a period included before the first use of the 'active-slide' class but not for the other two instances? var primary = ...

How to Easily Add GitHub NPM Packages to Your SAPUI5 Web IDE

Looking to integrate an NPM package from Github into SAPUI5 using the WebIde Framework. Package Link: https://github.com/commenthol/date-holidays/blob/master/README.md#usage Primary Issue: Need a file with the library for importing and copying into the W ...

Exploring Data in Angular 2: Examining Individual Records

I am currently learning Angular and facing some challenges in structuring my questions regarding what I want to achieve, but here is my query. Within a component, I am retrieving a single user record from a service. My goal is to display this user's ...

Remove a table along with its contents from HTML code using PHP

I'm working with some HTML code that includes a table, and I need to completely remove the table and its contents using PHP. While I know how to strip the table tags using PHP's strip_tags function, I'm not sure how to delete the table conte ...

Exploring the elements of Ext.js gridpanel and content components

Currently, I am diving into the world of Ext.js and finding it to be quite distinct from the asp.net ajax library despite some initial similarities. My goal is to populate a grid with test data formatted in JSON. The code snippet below illustrates my atte ...

Obtain the row ID from a database by selecting checkboxes

I am facing a challenge when trying to remove a row from my MS Access database using checkboxes on my JSP page. Each row in the displayed database has a checkbox, but I am struggling to retrieve the rowId and link each checkbox with its respective row. Any ...

What is the proper way to invoke express-validator within a middleware function?

I am facing a challenge in invoking the express-validator function from a middleware function. Although I can see that the execution is happening within the express-validator, validation does not seem to occur. The code snippet is provided below: router.g ...

Exploring Data in a Tree View Format on a PHP Website

Looking for advice on displaying categories and corresponding subcategories on the left side of my website (built using Php and Javascript). I would like the tree to be movable, similar to the functionality featured on this link: Any suggestions on how I ...

Getting rid of mysterious Google Analytics script from WordPress

My client has requested that I incorporate Google Analytics into her website. After accessing her Google account, I attempted to paste the tracking code into the appropriate section of the Wordpress plugin. To my surprise, the code did not work as expect ...

Adding elements within a loop using jquery

I am currently working on adding a toggle button using Javascript. I want to include three span tags inside it as well. To achieve this, I am creating a span variable and attempting to append it within a basic FOR loop that iterates 3 times. Below is the ...

Angular UI-router allowing links to direct to different sections of the same domain but outside of the app

I am currently working on implementing ui-router in my Angular application. The base URL I am using is "/segments" and I have defined it using the base tag. <base href="/segments" /> Below is my routing configuration: var base = "/segments" $sta ...

The ultimate guide to disabling iframe scrolling on Internet Explorer 8

After extensively searching for a solution, I realized that most answers focused on removing scrollbars rather than completely preventing the page from scrolling. My issue involves embedding an index.php file in an iframe on my website. Within the index.ph ...

The setTimeout function interrupts the event loop

Recently, I came across conflicting information regarding the usage of setTimeout to create nonblocking/asynchronous functions. One article suggested that using setTimeout is essential for this purpose, while another claimed that it actually blocks the eve ...