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

When attempting to access the Object data, it is returning as undefined, yet the keys are being

I have an Object with values in the following format: [ { NameSpace: 'furuuqu', LocalName: 'uuurur', ExtensionValues: 0, FreeText: 'OEN', '$$hashKey': 'object:291' }, { Nam ...

Leveraging Mongodb's aggregate feature to calculate the overall quantity of a specific product that has been ordered across all

Recently delving into the realm of javascript, I am currently tackling a dashboard project that requires displaying the total quantity of each product ordered. Although I have successfully defined a variable 'qty' to represent the quantity of an ...

Is the "add" feature malfunctioning?

My code is experiencing an issue where the URL and ID are not being passed correctly from one function to another. When I click on a link that contains the add() function, it fails to capture the URL and ID. <a href="#" style="color:#FFF;" onclick="add ...

Troubleshooting in WebStorm: Uncovering the Root Cause Within an npm Package (node:36378) [DEP0005] - Warning: Deprecation Warning

Over the past 6 months, I've been encountering an error that seems to have surfaced after an update to node.js. (node:36378) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), ...

What is the process for incorporating dynamic templates in AngularJS?

I have created 3 unique templates (DetailView, CardView, Column) for displaying content on a single page. Users can easily switch between these views. My goal is to display only one view at a time on the page. When the user switches views, I want to remov ...

AngularJS Partial Views: Enhancing Your Website's User Experience

As a newcomer to the world of Angular, I am seeking guidance on a specific issue. I have encountered a one-to-many relationship scenario where one Category can have multiple Product items. The challenge lies in my layout page setup where I display various ...

Using Cheerio with a Node.js bot

I am currently utilizing Cheerio to extract information from web pages in my .js files. However, I would like these files to automatically restart every 1 day to check for any new data. Instead of using setTimeout, which may not be efficient for managing ...

Visit a webpage on my site

Is it feasible to embed a website within another website? Suppose I have my index.html file. What if in the center of that file, we include an iFrame or similar element that loads , allowing users to explore Google directly on my website? ...

Is there a way for me to send a URL request from my website to a different server using PHP?

I am looking to initiate a request from my website to my server using a specific IP address. From there, I need the server to send another request to a different server and then display the response on the webpage. Can anyone provide guidance on how to ...

The controller element in AngularJS becomes undefined when invoked within a directive

Presented below is a snippet of my controller: myApp.controller('WizardController', function ($scope, $http) { $scope.user = { addressline1: null, cobuyer: null, validate: null, cobuyerfirstname: null, cobuyerlastname: null, ...

The dot operator cannot be used to access Json objects

Utilizing a4j jsFunction to transmit data to the server and receive JSON in return <a4j:jsFunction name="submitData" action="#{imageRetriveBean.saveData}" data="#{responseNodesPathsBean}" oncomplete="processData(event.data)"> <a4j:param name= ...

Saving Pictures in Database Without Using jQuery

Hey there fellow developers, I'm currently immersed in a web project that involves reconstructing a social media platform similar to snapchat. To capture images, I am utilizing my webcam with JavaScript and saving the image data to a variable named i ...

Can you explain the significance of the "@" symbol prefix found in npm package names?

While reading through the Angular Component Router documentation, I came across an npm command that caught my attention: npm install @angular/router --save I'm puzzled by the meaning of @angular/router. Is this entire string a package name? If so, ...

Is it possible to target the last child element in CSS without relying on nesting

Is there a way to select the very last child of an element and apply a specific class without using nesting? For instance, how can I target only the final div in the structure below, nothing more and nothing less. <body> <div class="very-last- ...

Dealing with an unexpected token error in JSON? Learn how to properly handle removing special characters like quotation marks and line breaks to

After receiving a JSON response from the server during page load, I successfully populate it on the page using Handlebars.js. However, I am facing difficulties in storing this JSON object in a JavaScript object. Here is what I tried: var jsObject = "{{o ...

Adaptive website backdrop

I have created a unique background for my website design, which includes 3 slices labeled as div id top, middle, and bottom. You can view the design in this image. I am interested in making this background responsive. While I have come across examples of ...

How can you set a condition for when no matches are found in a list filter?

I recently came across a fascinating example on W3 Schools that taught me how to implement a search filter. Below, I have customized it for everyone's reference. I am interested in modifying it to only display a list item with the message: No matche ...

There seems to be a request for an unknown parameter '1' in the data table row

My Datatable is structured as follows: <br><button id="addRow">Add New Row</button><br> <table class="table table-striped table-bordered table-hover " id="example" cellSpacing=0 width="100%"> <the ...

Exploring Multilingual Autocomplete or: Best Practices for Managing Multiple Languages in Web Applications

I'm currently developing a website and I have a mysql-table named 'items' with the following structure: item_id | item (The second column is used to identify the item_id.) In a file called language1.php, I have an array that stores the it ...

receiving an undefined value from a remote JSON object in Node.js

I have been struggling to extract the specific contents of a JSON api without success. Despite my best efforts, the console always returns undefined. My goal is to retrieve and display only the Question object from the JSON data. After spending several h ...