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

The socket.io.js file could not be located while using (nodejs with express [4.13] and socket.io [1.3])

Currently, I am utilizing express 4.13 and socket.io 1.3.2 along with an express generator. Here is the code snippet from my app.js: var app = express(); var server=require('http').createServer(app).listen(app.get('port'),'127.0. ...

Sending data from a PHP function to an AJAX call in the form of an associative array using json_encode() does not

Greetings, this is my first post so please forgive me if I miss anything or fail to explain clearly. All the code below is within the same PHP file. Here is my AJAX call: $.ajax( { type: "POST", url: window.location.href, data: {func: 'g ...

Determining the clicked node in a JavaScript environment

There are multiple spans with labels. <span class="viewEdit">View and edit class one.</span> <span class="viewEdit">View and edit class two.</span> <span class="viewEdit">View and edit class three.</span> <span clas ...

Managing iframes in React using reference methods

Trying to set the content of an iframe within a React component can be a bit tricky. There is a component that contains a handleStatementPrint function which needs to be called when the iframe finishes loading. The goal is to print the loaded iframe conten ...

Can you leverage the class declaration from a previous style in CSS when creating a new definition?

I have exhaustively searched for the solution without success, which is leading me to believe that it may not be achievable. With my limited understanding of CSS principles, I am inclined to think that this task could pose a challenge. However, before expl ...

Retrieving a targeted data point from a JSON object

I am working with a json data that contains various properties, but I am only interested in extracting the uniqueIDs. Is there a way to retrieve ONLY the uniqueID values and have them returned to me as a comma separated list, for example: 11111, 22222? (I ...

Adjust the visibility of components depending on the width of the screen

In my project, I have a Wrapper component that houses filters. This component becomes visible when the openMobileFilters() function is called and disappears when closeMobileFilters() is triggered. The Wrapper component occupies the entire page, and I want ...

Modify the length of an array using a number input field

Currently, I am working with an array that contains objects and I want to dynamically change the number of objects in this array based on user input from a number type input box. Whenever the number in the input box is increased, I need to increase the len ...

Adjust the color palette size when the zoom level is modified in the responsive mode within Angular

I am currently working with Angular 15 and attempting to adjust the color palette size depending on the zoom level. <input #primaryColor (change)="colorChange($event,'primary')" formControlName="primaryColor" class="co ...

Angular.js, require.js, and jQuery Plugin all combined to create a uniquely customized directive

As a newcomer to Angular and Require, I am seeking assistance with the following code snippet. Despite successfully integrating Angular and Require, I am facing an issue where the bootstrap-switch element fails to initialize: define(['myapp.ui/module ...

Making the navbar color modifications to the dropdown menu

I am currently working on applying color changes to the text in my navbar for the links that have been visited, are active, and are being hovered over. I have successfully implemented this for my regular hyperlink elements. However, I am facing an issue wi ...

Retrieving the information verified in the database

public function actionEditmul($id) { $sql1="SELECT * FROM category_product INNER JOIN category ON category_product.cat_id=category.cat_id WHERE category_product.product_id=$id"; $editcat=Yii::$app->db->createCommand($sql1)->quer ...

Can you set up an automatic redirect after a payment is made on paypal.me?

Is there a way to automatically redirect users to a "successful payment" landing page after they make a payment on paypal.me? While PayPal offers an "Auto Return" feature, I am uncertain if it is applicable for paypal.me or if there are alternative methods ...

Exploring the power of combining observables in RxJS

Having difficulty combining observables in my implementation of a tags-input feature. this._allTags represent all available tags. I am working with 4 streams: this._suggestions = new this.rx.Subject; this._searchText = new this.rx.Subject; this._s ...

The ellipsis text-overflow feature occasionally malfunctions during a single session when using IE 11

.show-ellipsis { white-space: nowrap; text-overflow: ellipsis; overflow: hidden; } <div class="container"> <div class="row show-ellipsis"> {{record.bodyName}} </div> </div> My web application supports versions o ...

Removing the root component in ReactJS can be done on specific pages by implementing

Is there a way to remove the <header/> and <footer/> components from my signup.js and signin.js pages without altering the root index.js file? Presently, the root index.js file looks like this: class Template extends React.Component { render( ...

Ways to position an absolute element in the middle of two CSS Grid cells

Is it possible to position an element with position: absolute between two grid cells, where half of the element is on the sidebar and the other half is on the rest of the page? The challenge arises when there is overflow set on both the sidebar and the pag ...

Tips for assigning a Custom Formik Component's value to the Formik value

I'm currently integrating Formik into my form alongside Google Places auto-complete feature. My goal is to display the places auto-complete functionality as a custom component within the Formik field. form.js <Formik initialValues={location:" ...

What is the proper way to reference automatically generated class names within nested style rules when using makeStyles in Material-UI?

When using makeStyles, how can I reference generated classnames when creating nested rules? For instance, if I have a "container" class with nested "item" elements and I want to use the generated "item" class in the style definition. The approach that wor ...

Element not producing output via Autocomplete from mui/material package

My challenge involves handling an array of states within the Autocomplete component. Once a state is selected, a corresponding component needs to be rendered based on the selection. However, despite successful state selection in the code, nothing is being ...