Using percentages for sizing and margins in CSS

Looking to create a visually appealing page that always fills the entire screen? Check out this code snippet that does just that:

#posts{
    width:100%;
    height:auto;
    background:#666;
}
.entry{
    float:left;
    margin-left: 4%;
    margin-top:10px;
    margin-bottom: 10px;
    width:20%;
    height:100px;
    background:#000;
}

However, there seems to be an issue with resizing the window. Despite using percentages for margins and sizes, it doesn't adjust correctly on window resize. Why is that so?

So my question is:

Why do CSS percentages not resize properly when the window size changes, and how can I fix it?

Make sure to resize your window after loading the page to witness the problem firsthand.

Take a look at the jsfiddle here

UPDATE:

After receiving some feedback, it appears that the issue stems from a conflict between my layout goals and masonry's absolute positioning of elements. To address this, I need a JavaScript/jQuery solution that can recalculate the margins based on correct percentages upon window resize. How can I achieve this?

Answer №1

It appears that the issue is related to the

position: absolute; property being applied by masonry.

An element positioned absolutely is removed from the document flow, not affecting the placement of other elements

By removing that line of code, the functionality should return to normal. You can see the updated result here

In cases where all elements have equal dimensions, using masonry may not be necessary.

UPDATE:

A script has been implemented to work with your existing html setup.

$(".entry").each(function(){
    var $this = $(this)
    var currLeft = 0;
    var containerWidth = 0;
    var newLeft = 0;

    currLeft = parseInt($this[0].style.left, 10);
    containerWidth = parseInt($("#posts").width(), 10);

    newLeft = currLeft/containerWidth * 100;

    $this.css({
        "left": newLeft + "%"
    })
});

This script converts the currLeft value from pixels to percentage for positioning.

Test the updated link

Answer №2

The reason for this issue is attributed to your masonry plugin. Please refer to this link for more information.

This particular plugin automatically sets the position and left top positions.

To resolve the issue, simply remove these properties.

Update:

Make changes to your code as follows:

HTML

<div id="posts">
    <div class="entry-content"><div class="entry"></div></div>
    <div class="entry-content"><div class="entry"></div></div>
    <div class="entry-content"><div class="entry"></div></div>
    <div class="entry-content"><div class="entry"></div></div>
    <div class="entry-content"><div class="entry"></div></div>
    <div class="entry-content"><div class="entry"></div></div>
    <div class="entry-content"><div class="entry"></div></div>
    <div class="entry-content"><div class="entry"></div></div>
    <div style="clear:both"></div>
</div>

CSS

#posts{
    width:100%;
    height:auto !important;
    background:#666;
}
.entry-content{
    float:left;
    margin-left: 4%;
    margin-top:10px;
    margin-bottom: 10px;
    width:20%;
    height:100px;
    background:#000;
}

Updated Fiddle: http://jsfiddle.net/Zpbsn/10/

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

Issue encountered when attempting to modify text with slideToggle()

I am struggling to update the text inside an element when toggling the visibility of a table. While I can toggle them successfully, changing the text within the element is proving to be a challenge. <table class="table funds-table"> <thead class= ...

Obtain the following image with every click

I have a div with images inside. I created two arrows (previous, next) within a larger div using the src of one of the images as the background URL for each arrow. My goal is to make the next arrow change the large image to the src of the following image w ...

What's the best way to add animation to the send icon while hovering over the button?

<div class="text-center"> <button [disabled]="btnStatus" class="btn btn-secondary buttonSend" type="submit"> <div [hidden]="btnStatus"> Send Message&nbsp;&nbs ...

What is the best way to retrieve a selected value from one dropdown list and populate it into another dropdown

Can someone assist me with retrieving the selected answer from one drop-down list and populating it into another drop-down list? Below is my code for programming groups A and B: Example: If a user selects an option from group A and group B, I would li ...

What is the best approach for making a drawer resizable?

I am interested in making the material ui drawer resizable width using a draggable handle. Currently, I have implemented a solution that involves adding a mouse event listener to the entire application and updating the width based on the position of the ...

Streaming videos on Xbox One is not supported while in developer mode

Currently, I am facing a challenge with my UWP app that runs a web application made for Xbox One. There is a bug that only appears after approximately 4 hours of streaming video content, causing the app to freeze unexpectedly on the machine. The issue lie ...

VueJS error: 'Property or method is not defined on the instance' message appears despite the method being defined on the instance

Is there a way in Vue.js to dynamically assign the class 'adjust' based on the value of a computed property called "isTrueSet"? I keep encountering the following error message: [Vue warn]: Property or method "itTrueSet" is not defined on the inst ...

Tips for pinpointing parent elements within a group of various sub child elements

CSS - <div class="windows" id="window'+divCount+'"> <p id="windowName'+divCount+'"></p> <p id="para'+divCount+'">Source</p> </div> <div cla ...

When is the appropriate time to utilize the style attribute in CSS?

Hey there, I'm in the process of building a website from scratch and I've hit a snag. I understand that using the style tag isn't ideal, but would it be acceptable in this scenario? Is there a more efficient approach? Let's consider t ...

I noticed that when I call my add function from the index view button in AngularJS, the counter value changes but it is not reflecting on the UI. Why is this happening?

FirstController.js function FirstController($scope) { $scope.$apply(function () { $scope.add = function (amount) { $scope.counter += amount; } });} The View - **Addtion.html** <div ng-controller="FirstController"> ...

The problem arises when the body/html element is narrower than the browser window

I encountered a strange issue while working on a website for a client/design studio. Despite setting the body and html elements to a width of 100%, I noticed that when I resize the browser, a scrollbar appears forcing me to scroll right. Upon scrolling, I ...

Is it necessary to restart the IIS Site when altering the contents of index.html?

I am currently working on updating a website that runs on a Custom Designed CMS with files using the .asp extension. The site seems to be quite dated and is hosted on an IIS Server, which I do not have direct access to. The user has requested some changes ...

Setting the "status" of a queue: A step-by-step guide

I created a function to add a job to the queue with the following code: async addJob(someParameters: SomeParameters): Promise<void> { await this.saveToDb(someParameters); try { await this.jobQueue.add('job', ...

Prisma unexpectedly updates the main SQL Server database instead of the specified database in the connection string

I have recently transitioned from using SQLite to SQL Server in the t3 stack with Prisma. Despite having my models defined and setting up the database connection string, I am encountering an issue when trying to run migrations. Upon running the commands: ...

Issue regarding custom CSS implementation in Angular project

Being a French speaker, I apologize in advance for any mistakes I might make. I am also fairly new to Angular, so if you could provide detailed explanations in your responses, it would be greatly appreciated. Thank you. I am trying to import a custom CSS ...

Determine the quantity of elements within a JSON object based on specified criteria

I am seeking a way to count the number of items in an array of JSON objects that meet specific conditions. The structure of my array is as follows: array = [{ name: 'Bob', age: 24 }, ...., { ...

AngularJs Controller with explicit inline annotation

I usually inject dependencies using inline annotations like this angular.module('app') .controller('SampleController',['$scope','ngDependacy',sampleController]); function sampleController($scope,ngDependacy) { ...

What is the JavaScript method for updating an HTML5 datalist to show new options?

When populating options dynamically into an HTML5 datalist, I'm facing an issue where the browser tries to display the datalist before all the options have loaded. As a result, the list either does not show up completely or only partially shows up. Is ...

Dynamic Styling in Angular 2/4: A Modern Approach

Can someone help me with Angular 2/4 syntax for this code snippet? $('nav ul li a').click(() => { $(this).closest('li').addClass('active'); }); ...

Guide to finding the parent component of a particular element?

When the add button is clicked, I am dynamically adding lists and a new button labeled as "New Button" to a web page. My goal is to have a variable printed inside the parent list when this "New Button" is clicked. How can I achieve this functionality? Bel ...