What are the best practices for utilizing CSS position (relative, absolute) combined with percentage dimensions for height and width?

There are numerous questions and answers related to this topic, but I have not come across a case like the one mentioned below. Everyone talks about setting the height and width in percentage by first setting the parent's height in percentage, but it still remains unclear to me.

For instance: consider the ID and class of a block in Drupal 7, and my code starting from "box1" which I added using the body (Editor) of that block.

<div id="block-block-1">
    <div class="block-inner">
        <div class="block-content">
            <div class="box1">
                <a class="box2">
                    <span class="box3">For Title</span>
                    <span class="box4">For Text</span>
                    <span class="box5">For Image</span>
                </a>
           </div>
        </div>
    </div>
</div>

**So, which part of the code is the parent for another?

  1. Height & width Aspect: Do I need to set #block-block-1 {height: 100%, width: 100%}, and will it apply to everyone? Or should I add it at each stage, but if I do that, then all div, a sections will automatically become 100%, which doesn't make sense.

  2. Position Aspect: Now, regarding the positioning aspect of Div using a combination of Position:relative and Position:absolute, where it is mentioned that the parent div should be relative and all divs inside it should be absolute with positions set using top, right, and left. But the same question arises - one's Relative position is another's absolute position, creating a contradictory scenario similar to the height and width issue.

So, what is the correct way to simultaneously use the height/weight (in percent) and position aspects?

Answer №1

Exploring some examples to gain insights into positioning and more, aiming to elevate your css-skills.

Prioritize reviewing the html code first to observe the outcomes

Start by understanding block-level/inline elements.

* {
  outline: 1px solid
}
div.iHaveKids {
  padding: 25px
}
/* all childs of div*/

div > * {
  background-color: red
}
b {
  background-color: yellow;
  width: 100%;
}
b.running {
  margin-left: 40px
}
span {
  background-color: pink
}
div.clearMe {
  width: 50px;
}
<div>This is a beautiful block-level element</div>
<span>This is an inline element</span>
<div>A block-level element's width is 100% if not set</div>
<div class="iHaveKids">A block-level element's height is designed to fit its children
  <div>I'm a child</div>
  <div>Me tooooooo</div>
  <div><b>A block element can have margins and/or paddings but I'm an inline element</b>
  </div>
  <div><b>Even when I have a width set, I just ignore them because I'm an inline element</b>
  </div>
  <div><b class="running away">However, I can set margin-left and/or margin-right</b>
  </div>
</div>
<span>I'm an inline element<span>me toooo and I'm inside an inline element</span>
<div class="clearMe">Block-level element</div>
<div>Block-level elements start at a new line in the document even if there is enough room</div>
</span>

Now let's dive into position:

* {
  outline: 1px solid;
}
div.example {
  background: red;
}
.example.ex1,
.example.ex2,
.example.ex3,
.example.ex4,
.example.ex5,
.example.ex10 {
  position: absolute;
}
span {
  background-color: yellow
}
div.ex4 {
  z-index: 2500;
}
.example.ex6,
.example.ex7,
.example.ex8,
.example.ex9 {
  position: relative;
}
.ex8,
.ex9 {
  top: 40px;
}
.ex9 {
  width: 500px;
  height: 500px;
}
.ex10 {
  bottom: 0;
}
<div>I'm a block-level element with default position: static</div>
<div class="example ex1">I'm an absolute element with position: absolute
  <span>My parent has an absolute position, I'm just an inline element</span>
</div>
<div class="example ex2">I'm an absolute element with position: absolute
  <span>My parent also has position: absolute. If no top, left, bottom or right is defined, I will place myself in the normal document flow without considering other positioned elements.</span>
  <span>If two or more position: absolute elements overlap, the latest one in the document-flow gets higher stacking order.</span>
</div>

... (remaining content) ...

<div class="example ex9">I have position: relative, I'm a block-element with a width of 500px and a height of 500px. I also have top: 40px;

  <div class="example ex10">I'm a block-level element with position: absolute inside an element with position: relative. I also have bottom: 0 so I position myself 0px away from the bottom line of my nearest positioned ancestor. If I have no nearest positioned ancestor, I take the document root.</div>

</div>

And now, discussing percentage width and height:

div {
  position: relative;
}
div > div {
  position: absolute;
}
div.parent {
  top: 10px;
  height: 400px;
  background-color: red;
}
div.child {
  background-color: yellow;
  top: 10%;
  bottom: 10%;
}
<div class="parent">
  I'm position: relative;

  <div class="child">
    I'm position: absolute;
    <br>Firstly, I look at top, right, bottom, left
    <br>Then, I consider my content and adjust even if I'm a block-level element
    <br>To calculate percentages, I refer to my parent
    <br>My parent has a height of 400px
    <br>Using top: 10%, meaning I will be positioned at 40px
    <br>
  </div>

</div>
Let's address your final question:

What is the correct approach for utilizing percentage width/height and position simultaneously?

Percentages are calculated based on the maximum available space. For instance, in the last example top: 400px;, therefore 10% == 40px. Once you comprehend how elements interact (root, parent, child, siblings, ancestors), executing such tasks becomes much simpler. Continuously read and learn about the disparities among various types of elements.

Do I need to set #block-block-1 {height: 100%, width: 100%}, for it to apply universally?

As mentioned in the examples, applying 'width: 100%' to a block-level element serves no purpose. Understanding how child elements respond to dimension settings requires knowledge of their type (block, inline, grid, flex, table, list, replaced,... element) and behavior.

Similarly, conflicting interpretations may arise when one considers Relative position as another's absolute position, echoing the dilemma between height and width.

An element with position: absolute; seeks the nearest positioned ancestor; if none is set, it defaults to the document.root. For further information, check out: Percentage guide on Mozilla CSS length properties on CSS-Tricks Distinguishing between “Block” and “Inline” elements on ImpressiveWebs

Answer №2

Here's a demonstration to help you grasp how it operates.

The main block .box2 is positioned 100px from the left side due to the margin.

If you wish to place elements using absolute, but in relation to .box2, you need to include position: relative on the parent element.

  • .box3 sits at a distance of 0px from the left edge of .box2
  • .box4 is situated 100px away from the left edge of .box2
  • .box5 stands 100px away from the right edge of .box2

You can also utilize the top and bottom properties as needed.

.box2 {
  border: 1px solid red;
  display: block;
  height: 2em;
  margin-left: 100px;
  position: relative;
  width: 400px;
}

.box2 span {
  border: 1px solid blue;
  position: absolute;
}

.box3 {
  left: 0;
}

.box4 {
  left: 100px;
}

.box5 {
  right: 100px;
}
<a class="box2">
  <span class="box3">For Title</span>
  <span class="box4">For Text</span>
  <span class="box5">For Image</span>
</a>

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

Forming triangles with outlines

Recently, I had the challenge of designing speech bubbles and found a clever technique to create the triangular tip at the end using CSS. By setting the element's width and height to 0 and playing around with borders, you can achieve diagonal shapes f ...

What is the most effective method for attaching text to an element without being affected by the spacing of other div elements

Seeking a method to add text after a textbox in-line, without being pushed to a new line by surrounding divs. The aim is for the text to remain close to the textbox, unaffected by wrapper div boundaries but still relative in position. Any viable solutions ...

Creating an HTML page that mimics the appearance of a PDF document across different screen sizes

I am working on a mock brochure/magazine/resume single page site and utilized bootstrap's container-fluid. The layout appears as follows - body div - container-fluid div - container-fluid row col-7 col-1 col Each column contains ...

The labels in production are getting cut off when creating a view in ASP .NET MVC

Upon viewing a Create View on my PC, I noticed that the main form and labels are adequately spaced: However, once the website is deployed to IIS and accessed on the same PC with the same browser, everything appears cramped in a smaller space. Is there a s ...

What's the best way to customize the color of the text "labels" in the Form components of a basic React JS module?

I have a React component named "Login.js" that utilizes forms and renders the following:- return ( <div className="form-container"> <Form onSubmit={onSubmit} noValidate className={loading ? 'loading' : ''}&g ...

Is it possible for a complete CSS ".class" to possess the specificity of '!important'? [closed]

It's quite challenging to determine the exact inquiry being made here. This question lacks clarity, precision, completeness, specificity, and is overly general or rhetorical, making it impossible to answer in its current state. To obtain assistance in ...

The Flask form within the Bootstrap input-group is breaking onto a new line when viewed on mobile devices

I want the 'Go' button to remain next to the search field. It displays correctly on Desktop view, but on mobile view, the submit button wraps (breaking up the input-group). How can I prevent this? Additionally, Bootstrap is adding gray lines aro ...

Aligning buttons in an inline form with Bootstrap

Issue with Button Alignment Post Validation. <form class="form-inline form-padding"> <div class="form-group"> <div class="input-group"> <input class="form-control" placeholder="First Name" name="fir ...

Unable to close expanded grid item using close button

Currently, I am working on a simple 3 column grid where each grid item consists of an image and a close button. The functionality I want to achieve is that when a grid item is clicked, the image should expand and the close button should become visible. Th ...

Should the event happen inside a div section

How can I determine if an element is currently positioned within a specific div? I am working on a vertical scrolling menu where the height of the navigation div is set and overflow is hidden to show only a portion of the links at a time. To navigate thr ...

Adding the Setting component to the Style Manager

I'm struggling to add component settings (traits) into the Style Manager panel section because of insufficient documentation. The way it is demonstrated in the demo is not clear to me. Is there a specific block of code that I should be using? I' ...

Images are not being shown on the desktop carousel display

I am encountering an issue with my carousel. When I attempt to decrease the height of the carousel, the entire image is not being displayed properly (on desktop), although it works fine on mobile devices. My goal is for the carousel not to take up the ent ...

Navigate to specific element from bootstrap navigation bar

I am in the process of creating a website for a small organization. The website is being constructed using bootstrap 4, and there is a navbar that connects to various flex-containers. I want these connections to smoothly scroll to their respective elements ...

How to place a scrollable content below a fixed flexbox navigation menu

I am struggling with a certain snippet (best viewed in full screen mode) where I need to position the <main> element directly underneath the <header> element. The <header> is set in a fixed position to remain at the top of the screen whil ...

I am looking to modify the background color of characters in a text box once the characters in a textarea exceed 150 characters

Currently, I am utilizing event.data to capture the text inputted into this particular HTML textbox. My intention is to change the background color to red based on that input. However, when using the style attribute on event.data, I encounter an error. It& ...

Utilize jQuery to apply a border and background color to a table row when hovering over it

Is there a way to change the border of a table row along with its background color when the mouse hovers over it? Currently, I can only modify the background color using the following code: $(document).ready(function() { $(function() { $(&apos ...

Toggle sidebar: expand/collapse

Looking for some assistance with my website project. I currently have two arrows to open and close the sidebar, but I would like one button to handle both actions instead. Can someone help me edit my code snippet to achieve this? Keep in mind that I am new ...

What is the best way to center my text vertically in each line?

I'm encountering an issue with aligning my text vertically in two lines within a <p> tag. I am trying to position the second line at the bottom of my <div>. I experimented with using vertical-align: bottom and text-bottom along with the to ...

Challenges with formatting the <legend> tag and grid setup in bootstrap 4

My intention was for it to be displayed like this: But unfortunately, it is appearing like this instead: You can see that the word "fruit" is misaligned. I am currently using Bootstrap 4 alpha v6. Here is the code snippet: <fieldset class="form- ...

CSS3 Arrow missing from display

Is there a way to create a box with an arrow on its right center using CSS? Here is the code I have so far, but the arrow is not displaying. Any suggestions? CSS: .pageHelp{ float:right; margin:10px 20px 0 0; width:85px; height:25px; border-radius:3px; b ...