Positioning elements at the bottom of the container

There is a dilemma that only those in the world of web development will understand. Beware!

I have envisioned a layout for a website I am constructing. The concept involves tilted <hr/> elements on the page, with text wrapping around them (refer to image below which illustrates this, where the black line signifies the <hr/>)

The design showcases orange stripes. Each stripe acts as a floating element with varying widths - starting from 10px, then 20px, and so forth. The black line marks their endpoint, delineating where they truncate the text.

The large orange space represents another floating element with a width of 0 and a height equal to 100% of its parent minus the aggregate height of the other 70 floating elements (the stripes), equating to 70px.

The conundrum: achieving this appears impossible. What currently occurs:

Due to each small stripe being 1px in height, they remain visible under any circumstance. However, the sizable element relies on its parent's height. Setting a fixed height for the parent solves the issue, but I desire a dynamically adaptable box which allows modifications to its internal text content. Furthermore, fixing the height results in disastrous visual impacts when scaling the webpage.

The desired outcome entails: The initial, substantial floating element should occupy the necessary space of (100% - 70px), without imposing a fixed height on its parent while still being floated.

I intend to reward the individual who solves this predicament with all the accolades within my capacity, given that it has plagued me for an extended duration.

To assist individuals attempting to resolve the matter, consider the following insights:

  1. Table cells can align elements to their baseline.
  2. Various rotation attempts initiated, yet unfortunately no provision for upside-down text.
  3. Experimented with margin, padding, and border combinations on the primary floating div - none proved effective thus far.
  4. The preference isn't for elements to float; this was merely the strategy undertaken due to a lack of knowledge regarding alternative methods for text wrapping around an element. Feel free to attempt any approach, as long as internal text adjustments are feasible, while ensuring consistent appearance regardless of scaling changes.
  5. Seems like employing Javascript to ascertain the required div height may be the sole solution.

All code consolidated into a Fiddle

EDIT: A potential solution has been identified, although programming execution remains unclear.

Through Javascript, the browser could calculate the container's content height (text, images, margins, etc.). Consequently, #lw ought to adjust to match that height. Subsequently, decrease #lw by 1px. Evaluate whether content height had altered upon reduction. If not surpassing the threshold of #lw's height + 70px, repetition ensues. Conversely, should the content height surpass previously mentioned limits, reduce #lw by 1px once more, halting the process. Upon window resizing, recommence the procedure.

This task seems daunting; were I versed in JS, I would willingly tackle it myself. Possibly enrolling at Codecadamy for enlightenment.

EDIT:

In the interim, a simpler version of the quandary emerges. Exploring css-shapes, revealed a means to accomplish what the 70 floating elements did utilizing a single entity. Additional set of files has been crafted, albeit necessitating a js file for functionality. HTML and CSS components provided below as code snippets; link appended for access to js code.

An automated height determination mechanism imperative in the coding structure. Included within depicts prescribed action through a <script> tag.

I begin to appear indolent, unable to contribute viable JavaScript directives.

HTML

<!doctype html>
    <html>
        <head>
            <meta charset="utf-8">
            <link rel="stylesheet" type="text/css" href="css/stylesheet.css">
            <script src='js/shapes.polyfill.min.js'></script>
        </head>
        <body>
            <div id="container">
                <div id="polybreak"></div>
                <p>
                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus enim arcu, porttitor vitae hendrerit euismod, efficitur pretium nulla. Sed a justo nulla. Aenean vel erat purus. In velit arcu, lacinia in justo in, vestibulum pellentesque mauris. Phasellus quis eros nunc. Vivamus fringilla euismod est, eget consectetur lacus cursus et. Fusce at arcu ac turpis laoreet feugiat nec a nulla.
                </p>
                <p>
                    Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque vehicula mollis leo non tempus. Praesent scelerisque dui felis. Suspendisse tristique, sapien egestas semper cursus, elit quam facilisis sapien, sit amet ornare odio nibh sed nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum libero nisi, efficitur id felis non, maximus ultricies sapien. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce rhoncus nibh enim, eget dignissim neque placerat et. Nam sit amet placerat sapien. Quisque vitae risus ac dolor porttitor tincidunt.
                </p>
                <p>
                    Nullam volutpat, lorem vitae ultricies lobortis, ligula ligula posuere erat, sed gravida sapien nisi non ante. Aliquam tellus sapien, placerat mollis tempor quis, consequat imperdiet magna. Etiam cursus ornare mauris sit amet varius. Sed dignissim euismod felis, at aliquet est fringilla at. Duis lorem nunc, imperdiet nec rhoncus et, egestas quis nunc. Nulla imperdiet elementum libero consequat tempor. Donec ante nunc, pellentesque nec ex dapibus, auctor sagittis ipsum. Phasellus ut est ex.
                </p>
            </div>
            <script src='js/shapes.polyfill.min.js'></script>
            <script type="text/javascript">
                On load and on resize:
                Make #polybreak the same height as #container + 60px.

                Subtract 1px off #polybreak''s height and check: is #container higher than #polybreak? If so, add 1px and stop. If not, repeat.
            </script>
        </body>
    </html>

CSS

html, body{
    margin: 0;
    padding: 0;
    height: 100%;
}

p{
    text-align: justify;
}

#container{
    width: 700px;
    margin: 0 auto;
}

#polybreak{
    width: 100%;
    float: left;
    shape-outside: polygon(0 calc(100% - 100px), 700px calc(100% - 1px), 700px 100%, 0 calc(100% - 99px));
}

Link to the raw js code https://raw.githubusercontent.com/adobe-webplatform/css-shapes-polyfill/master/shapes-polyfill.min.js

Answer №1

Many individuals are sharing JavaScript answers, so let's add a practical solution to the mix. The challenge when using JavaScript is that there is no clear method to 'calculate' the final height of #lw since predicting how text wrapping behaves can be difficult.

//Establish a good starting point
Zepto(".lW").hide();
var sh = document.getElementById("wrapper").scrollHeight;
document.getElementById("lw").style["height"] = sh - 60 + "px";
Zepto(".lW").show();

//Initiate the search
var height = parseInt(document.getElementById("lw").style["height"]);
var difference = Infinity;
var bestheight = 0;
var i = 0;
var checker = setInterval(function(){
    i++;
    height += 1;
    document.getElementById("lw").style["height"] = height + "px";
    var sh = document.getElementById("wrapper").scrollHeight;

    //The crucial part is finding the optimal situation instead of just 
    //the first instance where #lw exceeds the floats; our goal is to find 
    //the most efficient solution within a specific pixel range.
    // Here, that range is hardcoded as 30 pixels.
    if(Math.abs(height + 70 - parseInt(sh)) < difference){
        difference = Math.abs(height + 70 - parseInt(sh));
        bestheight = height;
    }
    if(i>30){
        clearInterval(checker);
        document.getElementById("lw").style["height"] = bestheight + "px";
    }
},0);

Check out the JSFiddle for the complete solution.

Answer №2

The latest trend in CSS includes its own dedicated feature set for handling these types of tasks called CSS Shapes. Adobe has even developed a helpful polyfill to support this module. Have you tried it out yet?

Answer №3

To control the height of the top div temporarily, give it a fixed height that matches the desired appearance of the non-angled text. It seems like the bottom div already has a fixed height of 70px.

<style type="text/css">
    #topPart { height: 600px }
</style>

To cater to varying screen heights, we need to calculate the correct dimension for the top div and subtract whatever space is needed at the bottom.

<script type="text/javascript">
window.onload=function(){
function resize()
{
    var windowHeight = window.innerHeight;
    document.getElementById("topPart").style.height = windowHeight - 70 + "px";
}
resize();
window.onresize = function() {
    resize();
};
}
</script>

The resizing function will be activated whenever the browser window changes, ensuring alignment between the top and bottom divs.

Add this basic structure in the HTML page:

<div id="topPart">
<p>Include any desired text or other elements here</p>
</div>
<div>
The staggered divs for the bottom section
</div>

Using percentages won't yield desired results, as you must account for the bottom portion's height. Initially, start by subtracting around 150 to 200px to avoid overflowing the bottom of the screen and causing layout issues. The page will respond dynamically, allowing for scaling up and down smoothly.

This is my interpretation of the instructions...

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

Finding the index of an element in an array using the filter method in Angular JavaScript

As I was working with an array of pages in a book, I wanted to find the index of a specific page that had been identified using filter. While my current function gets the job done, I can't help but wonder if there's a way to combine indexOf or fi ...

Execute a function with parameters when a button is clicked dynamically using PHP

I am trying to execute a parameterised function in PHP using AJAX. Below is the code snippet of my dynamic button where I need to pass $sub_id to the delet(sub_id) function for executing some SQL: echo "<td><input type='submit' name=&a ...

NodeJS reports an invalid key length, while C# accepts the key length as valid

Currently, I am in the process of converting Rijndael decryption from C# to NodeJS. The Key (or Passphrase) being used is 13 characters long, while the IV used is 17 characters long. Note: The length choice for both Key and IV is beyond my control Disp ...

Incorporate relationships while inserting data using Sequelize

vegetable.js ... var Vegetable = sequelize.define('Vegetable', { recipeId: { allowNull: false, ... }, name: { ... }, }); Vegetable.association = models => { Vegetable.belongsTo(models.Recipe); }; ... recipe.js ... var Recipe = sequeliz ...

Error 410: The Webpage has Disappeared

Unfortunately, my website fell victim to a hacking attack that resulted in the addition of numerous unwanted pages. These pages were quickly indexed by Google, causing a significant drop in traffic. The names of these pages all follow a similar pattern, s ...

Updating another component when an input value changes in React

I am currently learning React and I am facing a challenge in updating a component based on an input value. Previously, I had successfully done this using HTML and vanilla JavaScript. Now, I am trying to achieve the same functionality in React but encounter ...

JWT - Effective strategies for enhancing the user experience for a returning logged-in user

My client authentication system involves storing a JWT in `localStorage` once the user is verified. However, I'm not satisfied with the current user experience when a returning user is redirected straight to a new page without warning. window.locatio ...

Strange Behavior of SVG 'fill: url(#....)' in Firefox

I am struggling with an SVG graphic that I have created. Here is the code: <svg width='36' height='30'> <defs> <linearGradient id="normal-gradient" x1="0%" y1="0%" x2="0%" y2="100%"> <stop offset="0%" s ...

Error: Property 'blogCategory' is unreadable because it is undefined

Having trouble rendering blog posts from a json file in React const BlogPost = (props) => { const [post, setPost] = useState({ id: "", blogCategory:"", blogTitle:"", postedOn:"", ...

What is the best way to transform a list of Python+Flask objects into a list of JavaScript objects?

Here's a Flask application that showcases a list of objects. from flask import * app = Flask(__name__) class Entry: def __init__(self, name, surname): self.name = name self.surname = surname entries = [] entries.append(Entr ...

Are the server updates not syncing with the client browser?

Is there a reason why server updates are not appearing on the client browser? Could it be that a specific attribute value needs to be modified or is this related to caching? app.get('/hello' , (_ , res) => { res.header({ 'Cach ...

The event listener $(window).on('popstate') does not function properly in Internet Explorer

$window 'popstate' event is not functioning properly in IE when using the browser back button. Here is the code snippet used to remove certain modal classes when navigating back. $(window).on('popstate', function(event) { event.pre ...

How can we eliminate the modal-open class in Angular when transitioning to a different URL?

Currently, I am facing an issue with a bootstrap modal. There is a button inside the modal which upon clicking should navigate the current component to another component named 'questions'. The problem arises when the new component is loaded, as t ...

Automatically refreshing the canvas whenever the value of an HTML element is modified in Javascript

Below is the javascript code that is relevant <script> $.fn.ready(function() { var source = $('#source').val(); Meme('url1', 'canvas','',''); $('#top-line, #bottom-li ...

Automatically populate the next dropdown menu depending on the answer provided in the previous field

Can you help guide me in the right direction with 2 questions I have? If the answer to the first question is 1, then I would like the following answer to automatically be populated as Yes. Please assist me! <div class="field"> <!-- Number of Em ...

The Bootstrap navbar collapse fails to expand in the appropriate location

Whenever I try to expand the navigation on mobile mode by clicking the button, it doesn't push the content downwards. Instead, it just opens a small menu next to the button. Did I make a mistake in my code? <div class = "container"> ...

Assign the DatePicker Object to an HTML Element

I am currently using a SyncFusion date picker in my project and the implementation looks like this: var datepicker = null; $("#datepicker").hide(); $("#click").click(function(){ $("#datepicker").show(); datepicker = new ej.calendars.DatePi ...

ReactJS import duplication problem arising from utilizing npm link for component testing prior to npm package release

I have a basic component structured like this. import React, {useState} from 'react'; function MyComponentWithState(props) { const [value, setValue] = useState(0); return ( <p>My value is: {value}</p> ) } expo ...

In a Custom Next.js App component, React props do not cascade down

I recently developed a custom next.js App component as a class with the purpose of overriding the componentDidMount function to initialize Google Analytics. class MyApp extends App { async componentDidMount(): Promise<void> { await initia ...

Access the JSON data containing sub array values and showcase them on an HTML page by utilizing ngFor

Greetings! I am currently working on a web application where I need to showcase student data that is being received in JSON format. Below is the TypeScript code snippet that outlines the structure of the student data: export interface studentData{ ...