Diansheng
Diansheng

Reputation: 1141

best practice to replace css float, is it position:absolute?

I have read somewhere that floating is not recommended except for its initial usage, which is to float images around text.

So I conclude that, to make my child div stay at the right of my parent div, instead of using

child-div {
  float: right;
}

I should use

parent-div {
  position: relative;
}
child-div {
  position: absolute;
  right: 0;
}

Is this the best practice to replace float?

What if i have 5 child elements in one row? What should i use to replace float?

Thanks.
In case this question duplicates others, let me know

Upvotes: 4

Views: 7596

Answers (2)

Mike Trinh
Mike Trinh

Reputation: 1303

You can user flexbox in 2016;

.parent { display: flex; justify-content: flex-end }
<div class="parent">
  <div style="background:red">000</div>
  <div style="background:green">111</div>
  <div style="background:yellow">222</div>
  <div style="background:tomato">333</div>
</div>

Ofc you can add some styles so they have some space between them (child divs)

Upvotes: 3

user6409179
user6409179

Reputation:

Float is perfectly fine for what you're doing, so long as you clear the containing div to avoid layout issues.

Example HTML:

<div class="parent-div">
    <div class="child-div">Some text</div>
    <div class="child-div">Some text</div>
    <div class="child-div">Some text</div>
    <div class="child-div">Some text</div>
    <div class="child-div">Some text</div>
</div>

Example CSS:

.parent-div:after { clear: both; display: table; content: ""; }
.child-div { float: left; }

Alternatively, you can use display: inline-block instead of float.

Upvotes: 3

Related Questions