Hobbyist
Hobbyist

Reputation: 16212

Is it possible to apply a CSS style ONLY if a child class is present?

I'm using AngularJS and Cordova (ionic) in a mobile application project, and everything uses the same page perse. Everything is loaded into a single index.html file, so the body, html, ion-view, ion-content elements are all shared between each "page"/"interface"

Basically, all of my interfaces are set up with a unique identifier:

<ion-content id="interface-name">...</ion-content>

However, in this interface I need to make sure that the following elements have the following styles:

html, body, ion-view, ion-content, .scroll {
    height: 100%;
    overflow: hidden;
    margin: 0;
    padding: 0;
}

So that the interface can be fullscreen. This is all fine and dandy, but it's causing issues for my other interfaces not being able to scroll/expand vertically.

Is there a way (using CSS) to only apply a style if a child id/class is present, for example the above style is only applied if id="interface-name" is applied to a child element?

Upvotes: 5

Views: 6213

Answers (4)

0kMike
0kMike

Reputation: 373

There is a relatively new pseudo-class :has() that allows you to only apply css to an element, if a specific child (or children) is present.

Link to the mdn web docs

For example, you can apply a selector to an element of the class .list only, of a child with the class .list-item is present:

.list:has(.list-item) {
  display: block;
}

However, this feature is relatively new, and not all common browsers support that css selector yet: see the browser-compatibility

Upvotes: 6

Rob
Rob

Reputation: 15168

No. That's the "cascading" part of Cascading Style Sheets. It's a top down approach and you can't go back up the stream.

Upvotes: 1

Matt
Matt

Reputation: 3760

You could do it with a JavaScript function at page load time, but you can't apply CSS rules conditionally on the existence of child elements. Something simple like

var parent = document.getElementById("elementId").childNodes;
var children = parent.childNodes;
for(child in children) {
    if(child.id == "theIdYouAreLookingFor") {
        parent.style.height = "100%";
        // set other CSS rules here
        // ...
        break; // we're done, no need to check other children
    }
}

Upvotes: -1

Dominick Navarro
Dominick Navarro

Reputation: 752

If you want your code above to work on ID/class, for example apply only to id="interface-name"

#interface-name {
    height: 100%;
    overflow: hidden;
    margin: 0;
    padding: 0;
}

Upvotes: 0

Related Questions